简体   繁体   中英

Ruby YAML::load

I'm trying to modify the default deserialization of the built-in timestamp format, to affect Ruby's Time.

I do this (successfully) with Hash:

YAML::add_domain_type('yaml.org,2002', 'map') { |t, v| nil }
YAML::add_domain_type('ruby.yaml.org,2002', 'hash') { |t, v| nil }
hash = { :hello => :world }
puts YAML::load(hash.to_yaml) # nil

But when I try the same with Time, it doesn't work:

YAML::add_domain_type('yaml.org,2002', 'timestamp') { |t, v| nil }
YAML::add_domain_type('ruby.yaml.org,2002', 'time') { |t, v| nil }
puts YAML::load(Time.now.to_yaml).class # 'Time'

Any help would be appreciated. Thanks!

If you are using Psych (which is YAML in ruby 1.9.3p194) then you need to define an encode_with/1 method on the Time class.

require 'yaml'

class Time
  def encode_with(coder)
    coder.tag = '!ruby/time'
    coder.scalar = to_s
  end
end

YAML::add_domain_type('ruby.yaml.org,2002', 'ruby/time') { |t, v| "HELLO!!" }

yaml = YAML.dump(Time.new)  # -> "--- !ruby/time 2012-10-25 14:18:59 -0400\n...\n"
YAML.load(yaml)  # -> "HELLO!!"

If the encode_with/1 method is defined on the object then Psych calls that method passing in an instance of the Psych::Coder class; otherwise, it calls the visit_#{o.class} method in the YAMLTree class, which in the case of visit_Time does not serialize any tag information.

https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/yaml_tree.rb#l100-105

https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/yaml_tree.rb#l172-175

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM