Autoloading From “lib” In Rails 3
Rails does a great job of autoloading your files, and in the development environment it “re-autoloads” before every request by default. This means you don’t have to litter your files with require statements, and you don’t have to restart your development server every time you change a file. Changes take affect almost instantly, and everyone’s happy.
The “lib” folder is an exception to this rule (as, in fact, are most other folders outside “app”). This exception is intentional: mostly, it seems, this is to bring Rails app behaviour in line with Rails engine behaviour.
All good, but maybe you want Rails to autoload files from lib. Here’s how.
First, find the “config.autoload_paths” line in config/application.rb and change it to:
This adds “lib” to the autoload path.
Second, stop requiring your autoloaded files by hand. Say you want to autoload CoolExtensions from lib/cool_extensions.rb — then you need to stop using “require 'cool_extensions'” in your app. When you reference CoolExtensions in your code, Rails will automatically find and load lib/cool_extensions.rb.
Restart your development server, and you’re good to go.
From what I can gather, a lot of people understand the first step but not the second. My guess is that if you’ve already required a file, then Rails’ autoload behaviour won’t kick in.