自定义 to_yaml 和 domain_type [英] Custom to_yaml and domain_type
本文介绍了自定义 to_yaml 和 domain_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要定义用于序列化/反序列化对象的自定义方法.我想做类似以下的事情.
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?
推荐答案
好的,这就是我想出来的
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
这篇关于自定义 to_yaml 和 domain_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文