Forgive the overblown title, just leaving myself a quick note...

ActiveRecord::Base.metaclass.class_eval do
  def named_scope_with_existence_assertion(*args)
    named_scope_without_existence_assertion(*args)
    define_method("#{scope_name = args.first}?"){self.class.send(scope_name).exists?(id)}
  end
  alias_method_chain :named_scope, :existence_assertion
end

Usage:

class Item < ActiveRecord::Base
  named_scope :featured, :conditions => {:featured => true}
end

# obviously, this works...
Item.featured.find :all

# and now we get
Item.find(:first).featured? # does this instance satisfy the scope conditions?

Thanks for the idea, BB

 

Michael Cerna Chicago-based Rails Developer and Avid Musician. More ...

Search

Categories

  • Home (15)
  • Rails Plugins (5)
  • Pages (9)
  • Archives

    Tags

    BlogRoll