自定义to_yaml和domain_type

我需要定义自定义方法来序列化/反序列化对象。 我想做类似以下的事情。

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 

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

好的,这就是我想出来的

 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 

如果您只想序列化一部分属性,而不是所有属性,则可能需要使用to_yaml_properties