简体   繁体   中英

Rails 5: include unrelated class inside active admin's resource

I have Rails 5 API app with active admin that's working fine. I created a class in lib which calls app_languages.rb and contains array of hashes for language properties. I want to share the data in my active admin resources and use it, but It's not working. I tried writing require '/lib/app_languages.rb' but it's not working and I get this error: cannot load such file -- /lib/app_languages.rb

this is app_languages.rb:

class AppLanguages
  keys = [:language, :flag]
  values = ["English", "EN", "French", "FR", "Spanish", "SP", "Japanese", "JPN", "Hebrew", "HEB"]
  LANG = values.each_slice(2).map { |value| Hash[keys.zip(value)] }
end

How can I gain access to app_languages.rb's variables from a resource in active admin?

EDIT: I read that in rails 5 there's a problem with autoload so I already configured this in application.rb: config.autoload_paths << "#{Rails.root}/lib" and configured in every enviroment: config.eager_load = true

  • I would first change this from a class to a module: module AppLanguages .
  • Then change all 3 of the items to constants. KEYS VALUES LANG .
  • At the bottom of the file add ActiveAdmin.send(:include, AppLanguages) (or whichever module you would like the extensions in if not ActiveAdmin).
  • Finally, either have it in autoload or create an initializer to require it.

I recommend this method because you don't have to require it anywhere in ActiveAdmin itself, the code stays in your app. Also, if something in the module breaks (admittedly unlikely here) it will be easier to find the source of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM