Monday, June 16, 2008

Rails: Order of requiring libraries actually counts

While working on a Rails project, I got stuck in a very confusing problem. I simply wanted to define a cache sweeper. The well known definition of any cache sweeper is
class MySweeper < ActionController::Caching::Sweeper

To my surprise, I got an error: Uninitialized constant "ActionController::Caching::Sweeper"!!!! What the heck? Sweeper class is not defined.

After a significant period of time spent snorkeling in the code of Rails ActionController, I found the line where the Sweeper class is defined (actionpack-2.0.2/lib/action_controller/caching.rb - line 627).
if defined?(ActiveRecord) and defined?(ActiveRecord::Observer)
class Sweeper < ActiveRecord::Observer #:nodoc:

It turned out that the Sweeper class wasn't defined in my environment, just because ActiveRecord wasn't defined by the time 'action_controller' is required. I found out that actually I was requiring 'action_controller' before 'active_record'. I switched their order, and everything worked like a charm.

So, the bottom line is, ActiveRecord turned out to be a prerequisite for definition of certain classes and modules in other libraries like ActionController and ActiveSupport, so always require 'active_record' first.

No comments: