【发布时间】:2012-09-24 14:32:28
【问题描述】:
我有一个在 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 属性做同样的事情,给我上面看到的奇怪行为。
知道为什么会发生这种情况(以及如何解决它)吗?
【问题讨论】:
标签: ruby-on-rails ruby