[英]Ruby YAML::load
I'm trying to modify the default deserialization of the built-in timestamp format, to affect Ruby's Time. 我正在尝试修改内置时间戳格式的默认反序列化,以影响Ruby的时间。
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: 但是当我尝试使用Time时,它不起作用:
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. 如果您使用Psych(在ruby 1.9.3p194中为YAML),则需要在Time类上定义
encode_with/1
方法。
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; 如果在对象上定义了
encode_with/1
方法,那么Psych会调用传递Psych::Coder
类实例的方法; 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. 否则,它调用
visit_#{o.class}
的方法YAMLTree
类,它在的情况下visit_Time
不序列任何标记信息。
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#l100-105
https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/yaml_tree.rb#l172-175 https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/yaml_tree.rb#l172-175
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.