In the old days, we did this:

User.find(:all, :conditions => { :subscribed => true }, :order => 'created_at DESC' )

And then this:

User.find_all_by_subscribed(true, :order => 'created_at DESC' )

How about this?

User.for_subscribed(true).order_by('created_at DESC').find(:all)

Here’s the how!

class User < ActiveRecord::Base
  named_scope_for :subscribed
end

Whup-cha!

class ActiveRecord::Base
  def self.named_scope_for attribute
    named_scope "for_#{attribute}",
      lambda { |attribute_value| { :conditions => { attribute => attribute_value } } }
  end
 
  named_scope :order_by, Proc.new { |*attributes|
    raise ArgumentError, 'You must specify an attribute to order by' if attributes.blank?
    { :order => attributes.join(', ') }
  }
end

Check it out it here, or install using git.

git clone git://github.com/duncanbeevers/named_scope_for.git vendor/plugins/named_scope_for

2 Comments

  1. Jason Watkins

    Actually, both of the first two API’s were in the first versions of rails I used (0.5). I’m not sure one is older than the other.

    I think google app’s data api shows the next step: queries are classes.

  2. duncanbeevers

    Indeed, that seems to be exactly what’s being discussed in the ActiveRecord Refactoring wiki.

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.