Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5: Load lib files in production

My list of changes after moving to Rails 5:

  1. Place lib dir into app because all code inside app is autoloaded in dev and eager loaded in prod and most importantly is autoreloaded in development so you don't have to restart server each time you make changes.
  2. Remove any require statements pointing to your own classes inside lib because they all are autoloaded anyway if their file/dir naming are correct, and if you leave require statements it can break autoreloading. More info here
  3. Set config.eager_load = true in all environments to see code loading problems eagerly in dev.
  4. Use Rails.application.eager_load! before playing with threads to avoid "circular dependency" errors.
  5. If you have any ruby/rails extensions then leave that code inside old lib directory and load them manually from initializer. This will ensure that extensions are loaded before your further logic that can depend on it:

    # config/initializers/extensions.rb
    Dir["#{Rails.root}/lib/ruby_ext/*.rb"].each { |file| require file }
    Dir["#{Rails.root}/lib/rails_ext/*.rb"].each { |file| require file }
    

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/application.rb
...
# 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')!


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.


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


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')
...