自定义to_yaml和domain_type

发布于 2024-10-05 10:21:40 字数 283 浏览 0 评论 0原文

我需要定义用于序列化/反序列化对象的自定义方法。我想做如下的事情。

class Person
  def to_yaml_type
    "!example.com,2010-11-30/Person"
  end

  def to_yaml
    "string representing person"
  end

  def from_yaml(yaml)
    Person.load_from(yaml)
  end
end

声明序列化/反序列化的正确方法是什么?

I need to define custom methods for serializing/deserializing an object. I want to do something like the following.

class Person
  def to_yaml_type
    "!example.com,2010-11-30/Person"
  end

  def to_yaml
    "string representing person"
  end

  def from_yaml(yaml)
    Person.load_from(yaml)
  end
end

What's the correct way to declare the serialization/deserialization?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

空心↖ 2024-10-12 10:21:40

好的,这就是我的想法

class Person

  def to_yaml_type
    "!example.com,2010-11-30/person"
  end

  def to_yaml(opts = {})
    YAML.quick_emit( nil, opts ) { |out|
      out.scalar( taguri, to_string_representation, :plain )
    }
  end

  def to_string_representation
    ...
  end

  def Person.from_string_representation(string_representation)
    ... # returns a Person
  end
end

YAML::add_domain_type("example.com,2010-11-30", "person") do |type, val|
  Person.from_string_representation(val)
end

OK, here's what I came up with

class Person

  def to_yaml_type
    "!example.com,2010-11-30/person"
  end

  def to_yaml(opts = {})
    YAML.quick_emit( nil, opts ) { |out|
      out.scalar( taguri, to_string_representation, :plain )
    }
  end

  def to_string_representation
    ...
  end

  def Person.from_string_representation(string_representation)
    ... # returns a Person
  end
end

YAML::add_domain_type("example.com,2010-11-30", "person") do |type, val|
  Person.from_string_representation(val)
end
如果没有你 2024-10-12 10:21:40

如果您只想序列化属性的子集,而不是全部,则可能需要使用 to_yaml_properties

If you just want to serialize only a subset of properties, not all of them, you may want to use to_yaml_properties.

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