tags:

views:

109

answers:

1

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.

+1  A: 

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" )
paradigmatic