Thursday, April 2, 2009

(rails) naming chained named scopes

Is nobody doing this?

Rails named scopes are chainable, right? Here's a traditional example:
class Story < ActiveRecord::Base
named_scope :hilarious, :conditions => ["type = ?","comedy"]
named_scope :popular, :conditions => ["popularity_level > ?", 3]
end

and then you can ask for Story.popular.hilarious.all

But it didn't take much complexity for me to want to make a named scopes that represented a chain of named scopes.
Here's my first draft of a solution:

named_scope :hilarious_and_popular, lambda{ self.hilarious.popular.scope(:find) }


It's a little ugly, but it seems to work.

Story.popular_and_hilarious.all.should == Story.popular.hilarious.all