Rails 5: Load lib files in production

2019-01-08 03:34发布

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.

8条回答
再贱就再见
2楼-- · 2019-01-08 04:14

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)

# config/initializers/load_lib.rb
...
config.eager_load_paths << Rails.root.join('lib')
config.autoload_paths << Rails.root.join('lib')
...
查看更多
We Are One
3楼-- · 2019-01-08 04:16

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 my app directory as recommended on Github. Every folder in the app folder gets loaded by Rails automatically.

查看更多
\"骚年 ilove
4楼-- · 2019-01-08 04:21

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.

查看更多
SAY GOODBYE
5楼-- · 2019-01-08 04:21

There must be a reason that Autoloading is disabled in production by default.

Here is a long discussion about this issue. https://github.com/rails/rails/issues/13142

查看更多
ら.Afraid
6楼-- · 2019-01-08 04:23

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

查看更多
祖国的老花朵
7楼-- · 2019-01-08 04:24

I just used config.eager_load_paths instead of config.autoload_paths like mention akostadinov on github comment: https://github.com/rails/rails/issues/13142#issuecomment-275492070

# config.autoload_paths << Rails.root.join('lib')
config.eager_load_paths << Rails.root.join('lib')

It works on development and production environment.

Thanks Johan for suggestion to replace #{Rails.root}/lib with Rails.root.join('lib')!

查看更多
登录 后发表回答