0

我有 3 个模型:

Class Model1

end

Class Model2

end

Class Model3

end

我有这个代码:

scope :created_between, lambda { |start_time, end_time| where(:created_at => (start_time...end_time)) }

class << self
 ## Class methods for calculating searches
 def created_today
  today = Time.zone.now
  created_between(today.beginning_of_day, today.end_of_day)
 end

 def created_yesterday
  yesterday = Time.zone.now - 1.day
  created_between(yesterday.beginning_of_day, yesterday.end_of_day)
 end

 def created_last_week
  start_time = (Time.zone.now - 1.week).beginning_of_day
  end_time = Time.zone.now
  created_between(start_time, end_time)
 end

 def created_last_month
  start_time = (Time.zone.now - 1.month).beginning_of_day
  end_time = Time.zone.now
  created_between(start_time, end_time)
 end

 def created_last_year
  start_time = (Time.zone.now - 1.year).beginning_of_day
  end_time = Time.zone.now
  created_between(start_time, end_time)
 end

结尾

我需要将此代码添加到 3 个模型,但我不想在每个模型中重复代码。

我该怎么做?

非常感谢!

4

3 回答 3

6

尝试这个:

module CommonClassFunctions

 def self.included(base)
   base.send :extend, ClassMethods
 end

 module ClassMethods
   ## Class methods for calculating searches
   def created_today
    today = Time.zone.now
    created_between(today.beginning_of_day, today.end_of_day)
   end

   def created_yesterday
    yesterday = Time.zone.now - 1.day
    created_between(yesterday.beginning_of_day, yesterday.end_of_day)
   end

   def created_last_week
    start_time = (Time.zone.now - 1.week).beginning_of_day
    end_time = Time.zone.now
    created_between(start_time, end_time)
   end

   def created_last_month
    start_time = (Time.zone.now - 1.month).beginning_of_day
    end_time = Time.zone.now
    created_between(start_time, end_time)
   end

   def created_last_year
    start_time = (Time.zone.now - 1.year).beginning_of_day
    end_time = Time.zone.now
    created_between(start_time, end_time)
   end
  end
end

Class Model1
  include CommonClassFunctions
end

Class Model2
  include CommonClassFunctions
end

Class Model3
  include CommonClassFunctions
end
于 2012-11-08T15:04:01.763 回答
3

您可以使用此方法定义一个模块,然后将其包含在 3 个模型中。

喜欢 :

module Searcheable
  def created_today
    .
    . 
    .
    .
    .
  end
end

然后在课堂上:

class Model1
  extend Searcheable
end

class Model2
  extend Searcheable
end

class Model3
  extend Searcheable
end
于 2012-11-08T15:00:51.523 回答
0

你可以通过继承来做到这一点

class Model
  class << self
    def created_today
      puts "created today from Model"
    end
  end
end

class Model1 < Model

end

class Model2 < Model

end

class Model3 < Model

end

Model1.created_today
# output: created today from Model
于 2012-11-08T15:03:32.467 回答