7

It looks like this issue will be solved in Rails 4: http://blog.plataformatec.com.br/2012/08/eager-loading-for-greater-good/ but until then, I'm wondering how to eager-load modules/classes in my /lib.

In IRB it appears that they are loaded on-demand the first time I try to access:

Foo::Bar.constants
=> []

Foo::Bar::Service
=> Foo::Bar::Service

Foo::Bar.constants
=> [:ServiceBase, :Service]

I have several other classes in that module, and my code depends on being able to look them up using Foo::Bar.const_defined? at runtime - how do I ensure all Foo::Bar's classes get loaded at startup?

I'm already using config.autoload_paths += %W(#{config.root}/lib) in application.rb.

4

3 回答 3

9

Putting this in root/config/initializers/eager.rb should load all .rb files in that folder:

Dir["#{Rails.root}/lib/*.rb"].each {|file| load file}
于 2012-11-04T16:00:07.637 回答
6

For me putting this in application.rb solved the problem

config.eager_load_paths += Dir["#{config.root}/lib/**/"]
于 2016-03-08T05:56:30.777 回答
1

Use eager_load_paths combined with ActiveSupport::Reloader's to_prepare hook inside development.rb:

config.eager_load_paths += Dir["app/models/stimodel/**/*.rb"]  
ActiveSupport::Reloader.to_prepare do  
  Dir["app/models/stimodel/**/*.rb"].each { |f| require_dependency("#{Dir.pwd}/#{f}") }
end  

Adding your paths to eager_load_paths make sure that Rails loads them when it starts up. To make sure that Rails reloads our models if we do any changes or add new files, we also need to hook into the Reloader's to_prepare hook and manually require the dependency there.

于 2020-07-01T05:06:08.620 回答