Saturday, January 13, 2007

scope_out your models

After reading this excellent post on with_scope, I started using the with_x, find_x pattern all over the place. As a first step toward becoming a real contributing member of the rails community, I took the time to turn the pattern into a Rails plugin. And so scope_out was born.

Briefly, you would use scope_out like so:
class Thing < ActiveRecord::Base
scope_out :active, value => true

This simple declaration defines three class methods for you, like so:

def Thing.with_active
with_scope :find => {:conditions => ['active => ?', true]} do
def Thing.find_active(*args)
with_active {find(*args)}
def Thing.calculate_active(*args)
with_active {calculate(*args)}

There are 2 basic syntaxes for using scope_out. In the first, you may omit :field if the name of the field is the same as the name of the scope. :value can be a boolean, integer, or string. :conditions can take any of rails' normal condition syntaxes.

scope_out(:scope_name, :field => 'field_name', :value => value)
scope_out(:scope_name, :conditions => ['field => ?', value])

So there you have it, pure syntactic sugar. 100% meta. Enjoy!


Anonymous said...

excellent idea and i started using it. but i've
got "NoMethodError: protected method `with_active' called for User:Class" when i try with_...

scope_out :published, :conditions => ["is_published=1 and is_deleted=0"]

User.with_published {...} for example.

could you explain it?

Kris said...

May named_scope be a kind and benevolent ruler.

Kris said...

I'll miss you scope_out.