Scope Out Rails
Usage
1 class Thing < ActiveRecord::Base 2 scope_out :active, :field => 'active', :value => true 3 # in this case :field can be omitted since it matches the scope name 'active' 4 end
1 class Thing < ActiveRecord::Base 2 def Thing.with_active 3 with_scope :find => {:conditions => ['active => ?', true]} do 4 yield 5 end 6 end 7 8 def Thing.find_active(*args) 9 with_active {find(*args)} 10 end 11 12 def Thing.calculate_active(*args) 13 with_active {calculate(*args)} 14 end 15 end
with_x
Thing.with_active acts just like with_scope, except the scope is already defined.
For example:1 Thing.with_active do 2 Thing.find(:all, :order => 'stuff desc') 3 end
find_x
Thing.find_active acts just like find, except that it is scoped with with_active:1 Thing.find_active(:first, :include => :other_stuff)
is equivalent to
1 Thing.find(:first, :conditions => ['active = ?', true], :include => :other_stuff)
calculate_x
Thing.calculate_active (you guessed it) is exactly like Thing.calculate, but scoped with ‘with_active’1 Thing.calculate_active(:count, :all)
1 Thing.calculate(:count, :all, :conditions => ['active = ?', true])
Alternate Syntax
In addition, an alternate and more flexible syntax accepts the :conditions argument and passes it on to the scope methods. It will accept any form of the conditions argument that is valid for ActiveRecord::Base#find
1 class Stuff < ActiveRecord::Base 2 scope_out :teenagers, :conditions => 'age between 13 and 19' 3 end 4 5 Stuff.find_teenagers(:all)
- Repository Path: http://scope-out-rails.googlecode.com/svn/trunk/
- Homepage: http://code.google.com/p/scope-out-rails/
Tags
Currently tagged with:
You need to Login to tag this item.