只需要重定义该对象的
to_yaml_properties 方法, 只返回要序列化的字段就可以了
class A
attr_reader :a
attr_reader :b
def initialize(x,y)
@a = x
@b = y
end
end
a = A.new(1,3)
p a.to_yaml # => "--- !ruby/object:A\na: 1\nb: 3\n"
class << a
def to_yaml_properties
properties = super
properties.delete(:@a)
return properties
end
end
p a.to_yaml # => "--- !ruby/object:A\nb: 3\n"反序列化的方法是
obj = YAML.load(yaml);
本文介绍如何通过重定义to_yaml_properties方法来控制Ruby对象的YAML序列化过程,实现只序列化特定属性的目标,并提供了反序列化的示例。
12

被折叠的 条评论
为什么被折叠?



