加载使用 YAML 序列化的对象时调用 initialize [英] Calling initialize when loading an object serialized with YAML

查看:23
本文介绍了加载使用 YAML 序列化的对象时调用 initialize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在使用 YAML.load_file 时强制 Ruby 调用 initialize 方法?我想调用该方法以便为我没有序列化的实例变量提供值.我知道我可以将代码分解为一个单独的方法并在调用 YAML.load_file 后调用该方法,但我想知道是否有更优雅的方法来处理这个问题.

Is it possible to force Ruby to call an initialize method when using YAML.load_file? I want to call the method in order to provide values for instance variables I do not serialize. I know I can factor the code into a separate method and call that method after calling YAML.load_file, but I was wondering if there was a more elegant way to handle this issue.

推荐答案

我不认为你可以.由于您将添加的代码确实特定于要反序列化的类,因此您应该考虑在类中添加该功能.例如,让 Foo 成为您要反序列化的类,您可以添加一个类方法,例如:

I don't think you can. Since the code you will add is really specific to the class being deserialized, you should consider adding the feature in the class. For instance, let Foo be the class you want to deserialize, you can add a class method such as:

class Foo
  def self.from_yaml( yaml )
    foo = YAML::load( yaml )
    # edit the foo object here
    foo
  end
end

myFoo = Foo.from_yaml( "myFoo.yaml" )

这篇关于加载使用 YAML 序列化的对象时调用 initialize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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