【问题标题】:Dump ruby DateTime to YAML timestamp reliabely with ruby 1.8 and 1.9使用 ruby​​ 1.8 和 1.9 可靠地将 ruby​​ DateTime 转储到 YAML 时间戳
【发布时间】:2012-06-23 16:55:08
【问题描述】:

我有一个问题,YAML 在 ruby​​ 1.8 和 1.9 中的工作方式不太一样。尤其是在转储 DateTime 对象时。

Ruby 1.8:

require 'yaml'
YAML.dump(DateTime.now)
=> "--- 2012-06-21T14:29:02+02:00\n"

Ruby 1.9:

require 'yaml'
YAML.dump(DateTime.now)
=> "--- !ruby/object:DateTime 2012-06-21 14:29:41.874102975 +02:00\n...\n"

困扰我的是 !ruby/object:DateTime 标签,这很烦人。在 1.9 中使用 Time 对象解决了这个问题:

YAML.dump(DateTime.now.to_time)
=> "--- 2012-06-21 14:31:37.904841646 +02:00\n...\n"

问题在于 ruby​​ 1.8 中不存在 to_times。此外,ruby 1.8 Time 类不处理时区(不可能创建具有任意时区的 Time 对象)。

如果可能,我希望时间格式相同。

那我如何在 YAML 中转储 DateTime 对象?

【问题讨论】:

    标签: ruby datetime yaml


    【解决方案1】:

    在 Ruby 1.9.3 中,默认 YAML 引擎从 Syck 更改为 Psyck,但两者都可用。

    红宝石 1.9

    require 'yaml'
    YAML::ENGINE.yamler = 'syck'
    YAML.dump(DateTime.now)
     => "--- 2016-10-19T13:12:22+02:00\n" 
    

    如果您想在 Ruby 2.0 或更高版本中使用旧的 YAML 引擎(其中 Syck 肯定已被删除),您可以使用 gem syck

    Ruby 2.0:

    require 'syck'
    YAML.dump(DateTime.now)
     => "--- 2016-10-19T13:14:37+02:00\n"
    

    【讨论】:

      【解决方案2】:

      远非完美的解决方案是:

      class DateTime
        def to_yaml_time
          if DateTime.method_defined? :to_time
            # to_time is defined, and Time can be converted with timezones, perfect
            to_time
          else
            # We're a bit less lucky, but hopefully in this version of Ruby, DateTime
            # can be exported without garbage in the timestamp
            # ("!ruby/object:DateTime")
            self
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2015-03-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        相关资源
        最近更新 更多