There are numerous advantages to learning about the scope plugins available today for ruby on rails development. They can make your code DRYer and more readable and actually save you quite a bit af actual code. As you'll see when visiting the links I am providing with this post, the plugin scope_out for example can provide you with additional methods.
His sites example shows doing:
class Person < ActiveRecord::Base scope_out :women, :conditions => ['people.sex = ?', 'F'] end
The above code creates three class methods: findwomen, withwomen, and calculate_women. It is equivalent to doing the following:
class Person < ActiveRecord::Base def Person.with_women with_scope :find => {:conditions => ['people.sex => ?', 'F']} do yield end end def Person.find_women(*args) with_women {find(*args)} end def Person.calculate_women(*args) with_women {calculate(*args)} end end
There is more to scopeing issues in ruby on rails then what is presented in scope_out.
If your with_scope cases are in controllers as opposed to models, you can do for example:
class Movie < ActiveRecord::Base def self.with_playing with_scope :find => { :conditions => [ ‘state = ? AND visible = ?’, NOW_PLAYING, true ] } do yield end end end class MovieController < ApplicationController def director Movie.with_playing do @director = Movie.find(params[:movie_id]).director end end end
The following sites will open up a wide range of possibilites for you for best use cases for scope in ruby on rails:
The Scope Out Code and Project scope_out
Hobo creator insists you check out scope out... Here's why
Scoped Proxy Plugin for Ruby on Rails
Association Scope Plugin on Ruby on Rails Wiki
How to scope your controller without around_ filter (scope_out will allow you to do what this post explains in detail)
Here's an example using scoped_proxy.
class User < ActiveRecord::Base scoped_proxy :admins, :find => { :conditions => ['role = ?', 'super_user'] } scoped_proxy :has_login do |login| { :find => { :conditions => ['login = ?', login] } } end scoped_proxy :no_op do nil end end # This gives you the first administrator of the system User.admins.find(:first) # This counts the administrators User.admins.count # All users with a given login User.has_login('foo').count User.has_login('foo').find(:all, :order => 'created_at desc') # And finally, I give you the no op User.no_op.find(:all) # => User.find(:all)