Ruby YAML::加载
我正在尝试修改内置时间戳格式的默认反序列化,以影响 Ruby 的时间。
我用哈希(成功)做到了这一点:
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
但是当我用时间尝试同样的事情时,它不起作用:
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'
任何帮助将不胜感激。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 Psych(这是 ruby 1.9.3p194 中的 YAML),那么您需要在 Time 类上定义一个
encode_with/1
方法。如果在对象上定义了 encode_with/1 方法,则 Psych 会调用该方法并传入 Psych::Coder 类的实例;否则,它会调用
YAMLTree
类中的visit_#{o.class}
方法,在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#l172-175
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.If the
encode_with/1
method is defined on the object then Psych calls that method passing in an instance of thePsych::Coder
class; otherwise, it calls thevisit_#{o.class}
method in theYAMLTree
class, which in the case ofvisit_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