Thursday, February 15, 2007

More on scope_out

Dan Manges, one of my coworkers, wrote an excellent post on some of the reasons why you would want to use the scope_out plugin. You should go read it because he does a much better job of explaining it than I would. I just wanted to take this opportunity to point out some of the newer features that weren't included in the first release.

Dynamic conditions are now accepted if you pass a block to scope out. Notice how the block evaluates to a Hash. This is important because the block is evaluated each time the scope is called and the result is fed directly to Rails' with_scope method as the options parameter.

class Article < ActiveRecord::Base
scope_out :published_today do
{:conditions => {:publish_date => Date.today}}
end
end


You can combine scopes with a new method called (predictably) combined_scope. This method takes previously defined scopes which were created with scope_out and nests them in order to create a new scope.

class Person < ActiveRecord::Base
scope_out :software_developers, :conditions => {:job => "Software Developer"}
scope_out :ruby_programmers, :conditions => {:primary_language => "Ruby"}
combined_scope :happy_programmers, [:software_developers, :ruby_programmers]
end