2012-09-24 77 views
1

我有一個運行在Ruby 1.8.7上的Rails 3.2.6應用程序。該應用被配置爲使用中歐時間(即UTC + 2)作爲其時區,並且在我的初始化程序中,我使用了一些自定義功能的猴子補丁TimeDateTime在Rails中修改時間類導致時區混淆

奇怪的是,在我的猴子補丁方法中,Time/DateTime實例的行爲就好像它們是UTC(但使用時區調整值),但在應用程序中的其他位置,它們尊重時區配置。

所以,作爲一個例子,在config/initializers/monkey_patching.rb我有以下

module MonkeyPatching 
    def foo 
    inspect 
    end 
end 

class Time 
    include MonkeyPatching 
end 

class DateTime 
    include MonkeyPatching 
end 

現在,其他地方的應用程序(或軌道控制檯),這裏就是我得到

model.created_at.inspect #=> "Mon, 24 Sep 2012 15:06:34 CEST +02:00" (correct!) 
model.created_at.foo  #=> "Mon Sep 24 15:06:34 UTC 2012"   (all wrong!) 

所以,在model.created_at上直接撥打inspect可以給我正確的時區調整結果。但撥打修補方法foo - 這也只是叫inspect! - 將時間視爲UTC,即使它不是。

添加到我的困惑,這隻發生在模型屬性。即在導軌控制檯中,我得到了相同的結果 - 正確的結果爲DateTime.now.inspectDateTime.now.foo。但是爲DateTime屬性做同樣的事情,給我看上面的奇怪行爲。

任何想法爲什麼發生這種情況(以及如何解決它)?

回答

1

Rails使用ActiveSupport::TimeWithZone作爲時間屬性,而不是常規Ruby Time。也嘗試修補ActiveSupport::TimeWithZone

class ActiveSupport::TimeWithZone 
    include MonkeyPatching 
end 
+0

啊,當然!就是這樣 - 謝謝!我正在處理的應用程序在其業務邏輯中使用了大量「原始」時間/日期實例,因此我完全忘記了TimeWithZone – Flambino