Rails 3 Quicktip: Auto reload lib folders in development mode

One of our most popular article is “Rails 3 Quicktip: Autoload lib directory including all subdirectories, avoid lazy loading” in which we describe how autoloading the lib directory in Rails 3 can be done. However, one problem was still there, Rails 3 loads the lib directory on startup, but doesn’t reload the lib directory after that. Hence, if you change a lib file the server has to be restarted (which is quite annoying).

Here is how we can force Rails 3 to reload these files in Development Mode:

First we need to know which files we want to reload. For this purpose we create an initializer that goes through the lib directory and stores the path of all Ruby files:

Now we only need to reload these files on every request. The best place for doing so is the ApplicationController. So we create this before_filter:

The before filter runs only when the constant is defined (in our case in Development Mode) and reloads the file with the changes. No more restarting!

There are a couple of ways to reload the files, but I find this the least hackish way to do it. The downsides of this approach is that we have a before_filter in our ApplicationController that has nothing to do with the application logic and of course reloading all the files on every request slows things down. Nevertheless, not having to restart the server is really really helpful when developing in the lib directory.

See the quicktip in hemju Notes: http://notes.hemju.com/notes/rails-reload-lib-directory


Update 25.4.2011

I updated the ‘reload_lib’ GIST using the suggestions from James’ comment.