Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom to_yaml and domain_type

Tags:

ruby

yaml

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?

like image 280
opsb Avatar asked Nov 30 '10 20:11

opsb


1 Answers

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
like image 88
opsb Avatar answered Sep 18 '22 01:09

opsb