将自我类添加到模型rails 3中

时间:2012-11-08 14:56:22

标签: ruby-on-rails ruby ruby-on-rails-3

我有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个模型中,但我不想重复每个模型中的代码。

我该怎么做?

非常感谢!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

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

喜欢:

module Searcheable
  def created_today
    .
    . 
    .
    .
    .
  end
end

然后在课程上:

class Model1
  extend Searcheable
end

class Model2
  extend Searcheable
end

class Model3
  extend Searcheable
end

答案 2 :(得分: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