Extending Named Scopes

February 14th, 2009

Quick code tip…

I’m using named_scope with a lambda as the 2nd paramater, but I also want to extend the named_scope with some custom methods.

named_scope :for_league, lambda{|league_id| {league conditions} } do
  def default
  end
  def do_something_custom
  end
end

I use the same extended methods in more than one place, so I figured I’d use something similar to the :extend option used with association methods like has_many, but I can’t pass an :extend option if I’m also using a lambda.

The way around this is to just include the methods directly in the block.

module Associations
  def default
  end
  def do_something_custom
  end
end

named_scope :for_league, lambda{|league_id| {league conditions} } do
  include Associations
end

Works like a charm. Now I can just reuse the Associations module where I need it.


Your Response