How to extract common named_scopes from ActiveRecord models
Asked Answered
S

2

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?

Selfless answered 9/10, 2008 at 11:19 Comment(0)
R
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.

Rondelet answered 9/10, 2008 at 12:47 Comment(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?Grapery
T
0

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

Trill answered 17/10, 2012 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.