我有一个在 Ruby 1.8.7 上运行的 Rails 3.2.6 应用程序。该应用程序配置为使用欧洲中部时间(即 UTC+2)作为其时区,并且在我的初始化程序中,我使用一些自定义功能猴子修补 Time
和 DateTime
.
奇怪的是,在我的猴子补丁方法中,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
现在,在应用程序的其他地方(或在 Rails 控制台中),这就是我得到的
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,即使它不是。
更让我困惑的是,这只发生在模型属性上。 IE。在 Rails 控制台中,我得到了相同且正确的 DateTime.now.inspect
和 DateTime.now.foo
结果。但是对 DateTime 属性做同样的事情,给我上面看到的奇怪行为。
知道为什么会发生这种情况(以及如何解决)吗?
最佳答案
Rails 使用 ActiveSupport::TimeWithZone
作为时间属性,而不是常规的 Ruby Time
。也尝试修补 ActiveSupport::TimeWithZone
。
class ActiveSupport::TimeWithZone
include MonkeyPatching
end
关于ruby-on-rails - Monkey-patching Rails 中的 Time 类导致时区困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12567142/