Redline Software Inc. - Winnipeg's Leader in Ruby on Rails Development

Extending Named Scopes

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.

1
2
3
4
5
6
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.

1
2
3
4
5
6
7
8
9
10
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.

Comments