Can I use shared ActiveRecord regions (region) with a module in Rails?

In rails3, I do the same areas in the model. eg

class Common < ActiveRecord::Base scope :recent , order('created_at DESC') scope :before_at , lambda{|at| where("created_at < ?" , at) } scope :after_at , lambda{|at| where("created_at > ?" , at) } end 

I want to break common areas into a module in lib. So I try, like this one.

 module ScopeExtension module Timestamps def self.included(base) base.send :extend, ClassMethods end module ClassMethods scope :recent , lambda{order('created_at DESC')} scope :before_at , lambda{|at| where("created_at < ?" , at) } scope :after_at , lambda{|at| where("created_at > ?" , at) } end end 

and i write this

 class Common < ActiveRecord::Base include ScopeExtension::Timestamps end 

But Rails shows this error.

 undefined method `scope' for ScopeExtension::Timestamps::ClassMethods:Module 

(I did not forget the autoload of the library)

How can you easily reuse the general visibility feature in an active record?

I think this problem is related to the boot sequence. But I have no idea to decide. Please give me a hint.

+7
source share
2 answers

I decided that this calls the scope of self.included (class):

 module Timestamps def self.included(k) k.scope :created_yesterday, k.where("created_at" => Date.yesterday.beginning_of_day..Date.yesterday.end_of_day) k.scope :updated_yesterday, k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) k.scope :created_today, k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) k.scope :updated_today, k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) end end 
+8
source

In Rails 3, there is no difference between the declared scope and the class method that returns ActiveRecord::Relation , so it might be more elegant to use the mixin module:

 class MyClass < ActiveRecord::Base extend ScopeExtension::Timestamps end module ScopeExtension module Timestamps def recent order('created_at DESC') end def before_at(at) where('created_at < ?' , at) end def after_at(at) where('created_at > ?' , at) end end end MyClass.after_at(2.days.ago).before_at(1.hour.ago).recent 
+6
source

All Articles