我需要定义用于序列化/反序列化对象的自定义方法。我想做类似以下的事情。
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
声明序列化/反序列化的正确方法是什么?
答案 0 :(得分:5)
好的,这就是我想出来的
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
答案 1 :(得分:4)
如果您只想序列化一部分属性,而不是所有属性,您可能需要使用to_yaml_properties
。