Ruby on Rails 3 - Reload lib directory for each request

Nicolas Guillaume picture Nicolas Guillaume · Jul 19, 2010 · Viewed 24.6k times · Source

I'm creating a new engine for a rails 3 application. As you can guess, this engine is in the lib directory of my application.

However, i have some problems developing it. Indeed, I need to restart my server each time I change something in the engine.

Is there a way to avoid this ?

Can I force rails to completely reload the lib directory or a specific file and his requirements for each request ?

Thanks for your help :)

Answer

Patrick Hogan picture Patrick Hogan · Dec 6, 2010

I couldn't get any of the above to work for me so I dug in the Rails code a bit and came up with this:

New file: config/initializers/reload_lib.rb

if Rails.env == "development"
  lib_reloader = ActiveSupport::FileUpdateChecker.new(Dir["lib/**/*"]) do
    Rails.application.reload_routes! # or do something better here
  end

  # For Rails 5.1+
  ActiveSupport::Reloader.to_prepare do
    lib_reloader.execute_if_updated
  end

  # For Rails pre-5.1 
  ActionDispatch::Callbacks.to_prepare do
    lib_reloader.execute_if_updated
  end

end

Yes, I know it's disgusting but it's a hack. There might be a better way to trigger a full reload, but this works for me. My specific use case was a Rack app mounted to a Rails route so I needed it to reload as I worked on it in development.

Basically what it does is it checks if any files in /lib have changed (modified timestamp) since last loaded and then triggers a reload if they change.

I might also mention I have this in my config/application.rb

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Which just by default makes sure everything in my lib directory gets loaded.

Yays!