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

Use*_*159 9 ruby activesupport

我在Ruby 2.2.1上安装了active_support 4.2,所以我想使用它

Time.zone.parse('2007-02-10 15:30:45')
Run Code Online (Sandbox Code Playgroud)

如下所述: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
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

Ste*_*fan 7

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
Run Code Online (Sandbox Code Playgroud)


Gen*_*ume 6

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

建议的解决方案

require "active_support/all"
Run Code Online (Sandbox Code Playgroud)

如果您想查看active_support的源代码要塞,请查看github存储