Rails在模块中缓存Time.zone.now?

时间:2013-03-14 20:55:50

标签: ruby-on-rails

我有一个奇怪的错误,其中生产中的范围不能反映当前时间。

module TimeFilter
  # Provides scopes to filter results based on time.
  def self.included(base)
    base.extend(ClassMethods)
    base.class_eval do
      scope :today, where(end_time: Time.zone.now.midnight..Time.zone.now)
      scope :this_week, where(end_time: Time.zone.now.beginning_of_week..Time.zone.now)
      scope :this_month, where(end_time: Time.zone.now.beginning_of_month..Time.zone.now)
      scope :older_than_this_month, where("end_time < ?", Time.zone.now.beginning_of_month)
      scope :last_month, where(end_time: Time.zone.now.beginning_of_month..Time.zone.now.beginning_of_month - 1.month)
    end
  end
end

Time.zone.now似乎与rails控制台同时发生。

如果我将范围从库中移动到我的模型中,它可以正常运行。我做错了吗?

1 个答案:

答案 0 :(得分:1)

是的,您的范围正在class_eval进行一次评估。要纠正此问题,请为范围使用lambda,如下所示:

  scope :today, lambda {where(end_time: Time.zone.now.midnight..Time.zone.now)}
  scope :this_week, lambda {where(end_time: Time.zone.now.beginning_of_week..Time.zone.now)}
  scope :this_month, lambda {where(end_time: Time.zone.now.beginning_of_month..Time.zone.now)}
  scope :older_than_this_month, lambda {where("end_time < ?", Time.zone.now.beginning_of_month)}
  scope :last_month, lambda {where(end_time: Time.zone.now.beginning_of_month..Time.zone.now.beginning_of_month - 1.month)}

这将导致时间评估何时调用实际范围,而不是在调用eval时。