如何控制使用 YAML 序列化的字段 [英] How can I control which fields to serialize with YAML

查看:12
本文介绍了如何控制使用 YAML 序列化的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,

class Point
  attr_accessor :x, :y, :pointer_to_something_huge
end

我只想序列化 x 和 y 并将其他所有内容都保留为 nil.

I only want to serialize x and y and leave everything else as nil.

推荐答案

在 Ruby 1.9 中,to_yaml_properties 已弃用;如果您使用的是 Ruby 1.9,则更适合未来的方法是使用 encode_with:

In Ruby 1.9, to_yaml_properties is deprecated; if you're using Ruby 1.9, a more future proof method would be to use encode_with:

class Point
  def encode_with coder
    coder['x'] = @x
    coder['y'] = @y
  end
end

在这种情况下,这就是您所需要的,因为默认情况是在从 Yaml 加载时将新对象的相应实例变量设置为适当的值,但在更复杂的情况下,您可以使用 init_with:

In this case that’s all you need, as the default is to set the corresponding instance variable of the new object to the appropriate value when loading from Yaml, but in more comple cases you could use init_with:

def init_with coder
  @x = coder['x']
  @y = coder['y']
end

这篇关于如何控制使用 YAML 序列化的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆