I've upgraded one of my apps from Rails 4.2.6 to Rails 5.0.0. The Upgrade Guide says, that the Autoload feature is now disabled in production by default.
Now I always get an error on my production server since I load all lib files with autoload in the application.rb
file.
module MyApp
class Application < Rails::Application
config.autoload_paths += %W( lib/ )
end
end
For now, I've set the config.enable_dependency_loading
to true
but I wonder if there is a better solution to this. There must be a reason that Autoloading is disabled in production by default.
This allows to have lib autoreload, and works in production environment too.
P.S. I have changed my answer, now it adds to both eager- an autoload paths, regardless of environment, to allow work in custom environments too (like stage)
Autoloading is disabled in the production environment because of thread safety. Thank you to @Зелёный for the link.
I solved this problem by storing the lib files in a
lib
folder in myapp
directory as recommended on Github. Every folder in theapp
folder gets loaded by Rails automatically.For anyone struggled with this like me, it's not enough to just place a directory under
app/
. Yes, you'll get autoloading but not necessary reloading, which requires namespacing conventions to be fulfilled.Also, using initializer for loading old root-level
lib
will prevent reloading feature during development.Here is a long discussion about this issue. https://github.com/rails/rails/issues/13142
Moving the lib folder to app helped solve a problem, my Twitter api would not run in production. I had "uninitialized constant TwitterApi" and my Twitter API was in my lib folder. I had
config.autoload_paths += Dir["#{Rails.root}/app/lib"]
in my application.rb but it didn't work before moving the folder.This did the trick
I just used
config.eager_load_paths
instead ofconfig.autoload_paths
like mention akostadinov on github comment: https://github.com/rails/rails/issues/13142#issuecomment-275492070It works on development and production environment.
Thanks Johan for suggestion to replace
#{Rails.root}/lib
withRails.root.join('lib')
!