Rails 3: Auto Require

During the process of coding my blog, I came across the need for a truncation feature (another post in and of itself). So I made a new file under the lib directory called string.rb which added a truncate_html function to the String class. Lo and behold, whenever I called the function, the console printed an error stating that no such function existed.

In Rails 3, lib files are lazy loaded — this can be adjusted by adding the first line to the config/application.rb file. Restarted the server, but still I received the error.

Not only does Rails 3 no longer auto load the lib directory, but class extensions (as opposed to custom classes) are not auto required if the file name is that of a system class, which meant that the custom methods I defined for the String class are never added. To get around this, I made an initializer that simply auto requires any auto loaded files — config/initializers/auto_require.rb.

# config/application.rb
config.autoload_paths += "#{config.root}/lib"

# config/initializers/auto_require.rb
# Cycles through autoload_paths and requires them so that class methods are loaded
Rails::Application.config.autoload_paths.each do |d|
  Dir["#{d}/*.rb"].each do |p|
      puts "Auto-required #{p}"
      require p

Simple concept, but very useful as most lib files tend to be extensions of the core classes. We’ll see an application of this handy script when I write up on HTML truncation.