如何在我的模型中重复此代码

时间:2009-07-23 13:36:45

标签: ruby-on-rails model

我在模型中有这段代码,根据运行方法的时间设置开始日期和结束日期。

让我们直接进入代码示例:

#MODEL
now = Time.now
if now.hour >= 17 && now.hour <= 23
    #night
    n = now+1.day
    startd = Time.local(now.year, now.month, now.day, 17, 00, 00)
    endd = Time.local(n.year, n.month, n.day, 8, 00, 00)
elsif now.hour >= 0 && now.hour <= 7
    #morning
    n = now-1.day
    startd = Time.local(n.year, n.month, n.day, 8, 00, 00)
    endd = Time.local(now.year, now.month, now.day, 17, 00, 00)     
end

然后在模型中(相同或另一个),我试图在find中运行此函数。

#MODEL(SAME OR OTHER)
Model.find(:all, 
 :conditions => ['created_at >= ? AND created_at <= ?', startd, endd])

问题是我将使用该功能来设置很多开始和结束日期,我不知道在哪里放置它不重复自己。它将用于不同的模型。

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您可以将其包含在lib目录中的模块中。 RAILS_ROOT / lib中的所有ruby文件都会自动加载。

# time_calculations.rb

module TimeCalculations
  def calc_start_and_end_times
    now = Time.now
    if now.hour >= 17 && now.hour <= 23
        #night
        n = now+1.day
        startd = Time.local(now.year, now.month, now.day, 17, 00, 00)
        endd = Time.local(n.year, n.month, n.day, 8, 00, 00)
    elsif now.hour >= 0 && now.hour <= 7
        #morning
        n = now-1.day
        startd = Time.local(n.year, n.month, n.day, 8, 00, 00)
        endd = Time.local(now.year, now.month, now.day, 17, 00, 00)     
    end
    [startd, endd]
  end
end

# model.rb

class Model < ActiveRecord::Base
  extend TimeCalculations

  def self.my_find()
    startd, endd = calc_start_and_end_times
    Model.find(:all, 
      :conditions => ['created_at >= ? AND created_at <= ?', startd, endd])
  end

end

编辑以反映最终/正确答案。

答案 1 :(得分:1)

最简单的方法是将代码添加到模块中,也可以在初始化程序中添加:

module SmartDates

  def start_date
    now = Time.now
    if now.hour >= 17 && now.hour <= 23
      #night
      n = now+1.day
      return Time.local(now.year, now.month, now.day, 17, 00, 00)
    elsif now.hour >= 0 && now.hour <= 7
      #morning
      n = now-1.day
      return Time.local(n.year, n.month, n.day, 8, 00, 00)
    end
  end

  def end_date
    now = Time.now
    if now.hour >= 17 && now.hour <= 23
      #night
      n = now+1.day
      return Time.local(n.year, n.month, n.day, 8, 00, 00)
    elsif now.hour >= 0 && now.hour <= 7
      #morning
      n = now-1.day
      return Time.local(now.year, now.month, now.day, 17, 00, 00)
    end
  end

end

# Now include your module
ActiveRecord::Base.include(SmartDates)
ActionController::Base.include(SmartDates)

现在start_dateend_date在模型和控制器中均可用。

答案 2 :(得分:0)

你可以在模型类中添加方法find_by_date_range(startd,endd)并使用Model.find_by_date_range(something,something_else)