2013-03-14 60 views
1

我有一個奇怪的錯誤,其中生產範圍不反映當前時間。Rails在模塊中緩存Time.zone.now?

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

是的,你的範圍正在評估一次,在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被調用。

+0

謝謝。這樣可行。只是一個問題:lambda通常不需要參數?只是想明白。謝謝! – Hendrik 2013-03-14 21:11:10

+0

不! LAMBDA是速記[匿名函數(http://en.wikipedia.org/wiki/Anonymous_function) - 就像任何其他的功能,它可以接受任何數量的參數(包括零)。 – Veraticus 2013-03-14 21:21:47