为什么TimeWithZone对象根据它的创建方式采取不同的行为,特别是关于`.offset`?

时间:2017-08-28 15:41:05

标签: ruby-on-rails ruby

>> DateTime.now.in_time_zone.class
=> ActiveSupport::TimeWithZone
>> Time.zone.now.class
=> ActiveSupport::TimeWithZone
>> DateTime.now.in_time_zone.offset
=> (0/1)
>> Time.zone.now.offset
NoMethodError: undefined method `offset' for Mon, 28 Aug 2017 17:34:46 CEST +02:00:Time
    from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/activesupport-4.1.16/lib/active_support/time_with_zone.rb:364:in `method_missing'
    from (irb):287
    from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/console.rb:90:in `start'
    from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/console.rb:9:in `start'
    from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/commands_tasks.rb:69:in `console'
    from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
    from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

1 个答案:

答案 0 :(得分:2)

ActiveSupport::TimeWithZone没有offset方法。相反,该呼叫由method_missing处理:

  

将缺少的方法发送到time实例,并将结果包装到具有现有time_zone的新TimeWithZone中。

适用于DateTime,因为它会响应offset

DateTime.instance_methods.include? :offset
#=> true

Time失败,因为它没有:

Time.instance_methods.include? :offset
#=> false