Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling initialize when loading an object serialized with YAML

Tags:

ruby

yaml

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.

like image 990
Brian Young Avatar asked Dec 01 '09 00:12

Brian Young


1 Answers

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" )
like image 173
paradigmatic Avatar answered Nov 15 '22 05:11

paradigmatic