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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With