【问题标题】:undefined method `zone` for Time:Class after requiring active_support/time_with_zone需要 active_support/time_with_zone 后的 Time:Class 的未定义方法`zone`
【发布时间】:2016-05-05 14:45:14
【问题描述】:

我正在使用 Ruby 2.2.1 并安装了 active_support 4.2,所以我想使用

Time.zone.parse('2007-02-10 15:30:45')

如此处所述:http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html

但即使在要求active_supportactive_support/time_with_zone 之后,我似乎仍然无法使用Time.zone。观察:

2.2.1 :002 >   require "active_support"
 => true
2.2.1 :003 > Time.zone
NoMethodError: undefined method `zone' for Time:Class
2.2.1 :004 > require "active_support/time_with_zone"
 => true
2.2.1 :005 > Time.zone
NoMethodError: undefined method `zone' for Time:Class

发生了什么事?

【问题讨论】:

    标签: ruby activesupport


    【解决方案1】:

    active_support/time_with_zone 提供了ActiveSupport::TimeWithZone 类,但它没有扩展核心Time 类。

    您可以要求 active_support/time 代替:

    require 'active_support'
    require 'active_support/time'
    
    Time.zone = 'Eastern Time (US & Canada)' #=> "Eastern Time (US & Canada)"
    Time.zone.parse('2007-02-10 15:30:45')   #=> Sat, 10 Feb 2007 15:30:45 EST -05:00
    

    【讨论】:

    • 对于那些事后查看这个问题的人,我相信这是一个比我上面接受的答案更好的解决方案。感谢您发布 Stefan。
    【解决方案2】:

    Time 类的zone 类方法实际上在active_support/core_ext/time/zones 中。如果你真的想使用Time.zone,你可以要求该类,但更好的方法可能是要求active_support/all

    建议的解决方案

    require "active_support/all"
    

    如果你想查看 active_support 的源代码,请查看 github repo

    【讨论】:

    • require "active_support/all" => false
    【解决方案3】:

    试试

    require 'active_support/all'
    

    而不是

    require "active_support"
    

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多