Ruby YAML::加载

发布于 2024-09-20 00:05:14 字数 549 浏览 0 评论 0原文

我正在尝试修改内置时间戳格式的默认反序列化,以影响 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枉心 2024-09-27 00:05:14

如果您使用 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!!"

如果在对象上定义了 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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文