Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract common named_scopes from ActiveRecord models

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?

like image 910
Bartosz Blimke Avatar asked Oct 09 '08 11:10

Bartosz Blimke


1 Answers

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.

like image 64
Ben Scofield Avatar answered Nov 02 '22 23:11

Ben Scofield