Jigar
Jigar

Reputation: 9481

How to specify default values when loading files using yaml?

I saved a object of class Foo using foo.to_yaml. Now i added an instance variable to the Foo class with default value set to 0 in the initializer method. now when I try to load the object from yaml file the instance variable is set to nil.

Is there some way in which I can set it to 0 if the the yaml file doesnt contain any value for that instance variable?

Is there some callback method that is called on object after it has been loaded from disk?

Upvotes: 0

Views: 1148

Answers (1)

aivarsak
aivarsak

Reputation: 279

You can create reader method for that variable like

def your_instance_variable
    return "default" unless @your_instance_variable
    @your_instance_variable
end

P.S. I was doing some task with object serialization some time ago and AFAIK Marshal.dump/load was much faster

Upvotes: 1

Related Questions