Want to stay on top? Ruby Weekly is a once-weekly e-mail newsletter covering the latest Ruby and Rails news.
     Feed Icon

sexy_scopes: Syntactic sugar for ActiveRecord 3.0 and Arel

By Peter Cooper / June 20, 2010

sexy_scope is a small wrapper around Arel::Attribute that adds a little syntactic sugar when creating scopes in ActiveRecord. It adds an attribute class method which takes an attribute name and returns an Arel::Attribute wrapper, which responds to common operators to return predicates objects that can be used as arguments to ActiveRecord::Base.where.

Samuel Lebeau

Some sample code will clear up any confusion:

class Product < ActiveRecord::Base
  scope :untitled, where(attribute(:name) == nil)

  def self.cheaper_than(price)
    where attribute(:price) < price
  end

  def self.search(term)
    where attribute(:name) =~ "%#{term}%"
  end
end

sexy_scope reimplements Arel attribute methods like lt, in, matches and not using regular Ruby operators.

Comments

  1. Jon Leighton says:

    Cool. I gotta say I'm glad he hasn't chosen to add methods to Symbol, which is the approach taken by Mongoid, MongoMapper and DataMapper. Yeah, it's slightly less verbose, but it's so _wrong_!

  2. Ernie Miller says:

    Yeah, I seem to remember him saying he tossed it together because he didn't like that MetaWhere adds methods to symbol. I disagree that it's always evil to do so, particularly when there's little chance of namespace collision and the problem domain being addressed by the gem is well-defined... There's a fine line between best practices and dogma. ;)

Other Posts to Enjoy

Twitter Mentions