Reputation: 2750
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
.
Upvotes: 7
Views: 6811
Reputation: 10946
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.
Upvotes: 1
Reputation:
For me putting this in application.rb solved the problem
config.eager_load_paths += Dir["#{config.root}/lib/**/"]
Upvotes: 7
Reputation: 27779
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}
Upvotes: 9