使用ruby 1.8和1.9将ruby DateTime转储到YAML时间戳

时间:2012-06-21 12:44:15

标签: ruby datetime yaml

我有一个问题,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对象)。

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

我怎么能在YAML中转储DateTime对象呢?

2 个答案:

答案 0 :(得分:2)

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

Ruby 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"

答案 1 :(得分:0)

远非完美的解决方案是:

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