Rails 3: How to Autoload and Autorequire your Custom Library Code

Every time I start a new Rails 3 project, I’m always caught out by its autoloading behaviour. Rails 3 will only require (and so autoload) a module when it is first encountered within the application code, for example by a call to include or require.

Whilst the reasoning behind this decision is sound, I usually just want to load some common functionality into, for example ActiveRecord, and have it available to all of my models.

So, as a reminder to myself and to help anyone else caught out by this, here is how to autoload (and autorequire) your own library code in Rails 3:

Ensure that your library code’s path is set in config/application.rb. By default, Rails 3 autoloads from a /extras folder, but I conventionally keep custom library code in a /lib folder:

# config/application.rb
config.autoload_paths += %W(#{config.root}/extras #{config.root}/lib)

Next, we need to tell Rails to require our library code (so it is available to the application). Create a new initializer called application.rb in config/initializers and require your library modules:

# config/initializers/application.rb
require 'my_modules'
require 'my_modules/active_record/active_record_extensions'
# ... require any other custom modules your application uses

All that’s left to do is restart your Rails server to load your custom modules into the application. Remember that if you change your custom code, you’ll need to restart the server again to reload the changes.

  • Threadhead

    Perfect timing, gracias!

  • http://twitter.com/yukas Yuri Kasperovich

    Hi, Chris. What should I do to reload my library code on every request?

    • http://chrisblunt.com/ Chris Blunt

      Hi Yuri,

      Unfortunately I don’t know of a clean way to reload library code on every request, which is quite annoying when developing library code.

      What I’ve done is to develop library code under one of the standard Rails code folders (e.g. /app/models/my_modules) which means it gets reloaded with each request. Once the library is working, move it back under /lib the lib folder and add the appropriate “requires” as in the post.

  • Ping Li

    Hello, Chris! Your post is concise and beautiful, but I was confused by it. If I want to reload the code in lib directory without restarting server, what should I do.

    • http://chrisblunt.com/ Chris Blunt

      Hi Ping, unfortunately you will need to restart the server to load the new config/initializers code.