【问题标题】:Monkey-patching the Time class in Rails leads to time zone confusion在 Rails 中对 Time 类进行猴子修补会导致时区混乱
【发布时间】:2012-09-24 14:32:28
【问题描述】:

我有一个在 Ruby 1.8.7 上运行的 Rails 3.2.6 应用程序。该应用程序配置为使用欧洲中部时间(即 UTC+2)作为其时区,并且在我的初始化程序中,我使用一些自定义功能对 TimeDateTime 进行了猴子补丁。

奇怪的是,在我的猴子补丁方法中,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.inspectDateTime.now.foo 的相同且正确的结果。但是对 DateTime 属性做同样的事情,给我上面看到的奇怪行为。

知道为什么会发生这种情况(以及如何解决它)吗?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    Rails 使用 ActiveSupport::TimeWithZone 作为时间属性,而不是常规的 Ruby Time。也尝试修补ActiveSupport::TimeWithZone

    class ActiveSupport::TimeWithZone
      include MonkeyPatching
    end
    

    【讨论】:

    • 啊,当然!就是这样-谢谢!我正在处理的应用程序在其业务逻辑中使用了很多“原始”时间/日期实例,所以我完全忘记了 TimeWithZone
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2013-12-26
    • 1970-01-01
    • 2016-10-30
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多