时间的未定义方法`zone`:需要active_support / time_with_zone后的类

时间:2016-01-28 09:44:10

标签: ruby activesupport

我在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

发生了什么事?

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:5)

zone类的Time类方法实际上位于active_support/core_ext/time/zones。如果您真的想使用Time.zone,则可以要求该类,但更好的方法可能需要active_support/all

建议的解决方案

require "active_support/all"

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

答案 2 :(得分:2)

尝试

require 'active_support/all'

而不是

require "active_support"
相关问题