12

I have named_scope which is reused in multiple ActiveRecord models. For example:

  named_scope :limit, lambda {|limit| {:limit => limit}}    

What is the best practice to extract this code to be shared across models. Is it possible to extract it to a module or should I rather reopen ActiveRecord::Base class?

Bartosz Blimke
  • 6,498
  • 3
  • 24
  • 19

2 Answers2

21

Use a module. Something like this should work:

module CommonScopes
  def self.included(base)
    base.class_eval do
      named_scope :limit, lambda {|limit| {:limit => limit}}
    end
  end
end

Then just include CommonScopes and you'll be good to go.

Ben Scofield
  • 6,398
  • 2
  • 23
  • 22
  • 1
    This seems to work for the class-level, but not the instance-level. For example: `User.limit(1)` works, but the second call to limit here raises an error: `users=User.limit(5); users.limit(1)`. Any solution for the instance level? – Matt Huggins Apr 18 '11 at 17:14
0

@Matt via instance_eval, @see Shared scopes via module?

Community
  • 1
  • 1