Thursday, May 14, 2009

Scopes for conditions


It is common for your named and anonymous scopes to only specify the :conditions option. In RailsCast #112, Ryan Bates suggests adding a conditions named_scope:


This allows you to replace:
active_people = People.scoped(:conditions => {:active => true})
with:
active_people = People.conditions(:active => true)

A step further

This can be taken a step further by adding a class method, named_conditions, to ActiveRecord::Base:


Now you can replace:
class Post
named_scope :recent, lambda { {:conditions => ['created_at > ?', 1.day.ago] } }
end
with:
class Post
named_conditions :recent, lambda { ['created_at > ?', 1.day.ago] }
end

Not very exciting, but it's the little things that count. You can download the module at http://gist.github.com/111783.

0 comments: