Time:Class 需要 active_support/time_with_zone 后未定义方法 `zone`

问题描述 投票:0回答:4

我使用的是 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_support
active_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
4个回答
9
投票

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

建议的解决方案

require "active_support/all"

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


8
投票

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

2
投票

尝试

require 'active_support/all'

而不是

require "active_support"

0
投票

如果您不想加载所有主动支持:

require "active_support"
require "active_support/core_ext/numeric/time"
© www.soinside.com 2019 - 2024. All rights reserved.