【问题标题】:Why use Time.current over Time.zone.now in Rails, when Time.zone is always set?为什么总是在设置 Time.zone 时在 Rails 中使用 Time.current 而不是 Time.zone.now?
【发布时间】:2018-01-26 09:23:24
【问题描述】:

Time.current 的文档说:

当设置了Time.zoneconfig.time_zone 时返回Time.zone.now, 否则只返回Time.now

# File activesupport/lib/active_support/core_ext/time/calculations.rb, line 36
def current
  ::Time.zone ? ::Time.zone.now : ::Time.now
end

但是Time.zone 什么时候没有在 Rails 中设置?

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Berlin'

我已经注释掉了config.time_zone,我仍然得到等于'UTC'的Time.zone,因为它显然在注释中提到了默认设置。那么,使用Time.current 而不是Time.zone.now 有什么意义呢?

PS:我在 Rails 4.1.16 上观察到这一点

【问题讨论】:

    标签: ruby-on-rails time timezone


    【解决方案1】:

    简短的回答是,如果您按原样使用Rails,除了更简洁/更短的语法之外没有区别。

    Time.zone_default 通过active_support.initialize_time_zoneActiveSupport::Railtie 中初始化。有关 railtie 初始化过程的更多信息here

    我对此检查的猜测是,作为一个框架,它考虑了有人从他们的 Rails 启动过程中删除了这个 active_support.initialize_time_zone 的情况。在这种情况下,Time.zone 将是 nil

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 2010-10-30
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      相关资源
      最近更新 更多