【问题标题】:Setting up Time.zone in Padrino在 Padrino 中设置 Time.zone
【发布时间】:2014-06-22 22:31:35
【问题描述】:

我在我的 padrino 项目中设置默认 ActiveSupport::TimeZone 时遇到问题。

在我的 boot.rb 中有

Padrino.after_load do
  Time.zone = 'UTC'
  ActiveRecord::Base.default_timezone = :utc
end

我的控制器文件有:

MyApp::App.controllers :post do
  get :index do
    puts Time.zone # this returns nil
    render 'index'
  end
end

当我点击索引操作时,Time.zone 的值为零。似乎某些东西可能会覆盖 Time.zone 或未正确加载。

  • 在 boot.rb 中设置时区后,我可以打印出来。所以我知道它已经设置好了。

【问题讨论】:

  • 嘿 Moemars,你解决了这个问题吗?
  • 不,我没有。在控制台中,它按照下面的建议工作,但在控制器中却没有。
  • 对我来说也一样。在测试中有效,但在我在 dev 中运行实际的 Web 应用程序时无效:/

标签: ruby timezone padrino


【解决方案1】:

你可以这样设置:

Time.zone_default = Time.find_zone!("UTC")

这就是您所需要的,但请参阅下文了解详细信息。

以上内容适用于我的 activesupport 5.0.2。我查看了Time.zone 是如何实现的:

class Time
  include DateAndTime::Zones
  class << self
    attr_accessor :zone_default

    # Returns the TimeZone for the current request, if this has been set (via Time.zone=).
    # If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
    def zone
      Thread.current[:time_zone] || zone_default
    end

然后我猜测它可能在当前与 Padrino 的线程中丢失。

大概Time.zone 需要为每个线程设置一次。无论出于何种原因,在Padrino.before_load 中分配区域时并非总是如此。我没有深入研究这一点,但我确信有一个更好的解决方案可以在每个线程中分配它。

如果您想要每个用户的时区,而不仅仅是整个应用程序的全局时区,您需要进一步挖掘。

【讨论】:

    【解决方案2】:

    在我的boot.rb 我有:

    Padrino.before_load do
      Time.zone = 'UTC'
    end
    

    在我的database.rb:

    ActiveRecord::Base.default_timezone = :utc
    

    在控制台中测试过的似乎可行:

    ruby-2.1.4$ padrino c
     => Loading development console (Padrino v.0.12.4)
    2.1.4 :001 > Time.zone 
     => #<ActiveSupport::TimeZone:0x007fbff62ed5c0 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffset: 0,0,UTC>>>> 
    2.1.4 :002 > Time.zone.now
     => Tue, 30 Dec 2014 13:14:57 UTC +00:00 
    2.1.4 :003 > Time.current
     => Tue, 30 Dec 2014 13:15:01 UTC +00:00 
    2.1.4 :004 > ActiveRecord::Base.default_timezone
     => :utc 
    

    注意使用 ruby​​ v2.1.4、padrino v0.12.4、activesupport/activerecord v4.2.0 测试。

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多