Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active January 19, 2024 15:00
Show Gist options
  • Save maxivak/381f1e964923f1d469c8d39da8e2522f to your computer and use it in GitHub Desktop.
Save maxivak/381f1e964923f1d469c8d39da8e2522f to your computer and use it in GitHub Desktop.
Load code in libraries in Rails 5

Load lib files in production (Rails 5)

If you have your code defined in classes in lib/ folder you may have problems to load that code in production.

Autoloading is disabled in the production environment by default because of thread safety.

Change config/application.rb:

    config.autoload_paths << Rails.root.join("lib")
    config.eager_load_paths << Rails.root.join("lib")

It works in development and production environments. eager_load_paths will get eagerly loaded in production and on-demand in development. Doing it this way, you don't need to require every file explicitly.

Recommendations: (from https://stackoverflow.com/questions/38198668/rails-5-load-lib-files-in-production)

  • 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.

  • 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

  • Set config.eager_load = true in all environments to see code loading problems eagerly in dev.

  • Use Rails.application.eager_load! before playing with threads to avoid "circular dependency" errors.

  • 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 }

References:

@javierojeda94
Copy link

But is it recommended to move lib inside app... It seems dirty and more like a patch than a solution.

I don't think it is a valid way to solve that lib loading issue :/

@igbanam
Copy link

igbanam commented Jan 4, 2020

I agree that moving the lib directory inside the app directory is a bad idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment