Rails 5: Load lib files in production

Tobias picture Tobias · Jul 5, 2016 · Viewed 78.4k times · Source

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.

Answer

Lev Lukomsky picture Lev Lukomsky · Oct 13, 2016

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 }