自定义to_yaml和domain_type

ops*_*psb 6 ruby yaml

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

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
Run Code Online (Sandbox Code Playgroud)

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

ops*_*psb 6

好的,这就是我提出的

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
Run Code Online (Sandbox Code Playgroud)


And*_*imm 5

如果您只想序列化属性的子集,而不是全部,则可能需要使用to_yaml_properties.

  • 请注意,这应该是实例变量名称的列表,例如“%w[ @foo @bar ]” (2认同)