Omitting Variables on Saving

If, for some reason, you want to omit some instance variables when serializing objects, you can do so by defining a method named to_yaml_properties. In the body of this method, place an array of strings. Each string should match the name of the instance variable to be saved. Any variables that are not specified will not be saved. Take a look at this example:

limit_y.rb

class Yclass
    def initialize(aNum, aStr, anArray)
        @num = aNum
        @str = aStr
        @arr = anArray
    end

    def to_yaml_properties
        ["@num", "@arr"]     #<= @str will not be saved!
    end
end

Here to_yaml_properties limits the variables that will be saved when you call YAML.dump to @num and @arr. The string variable, @str, will not be saved. If you want to reconstruct the objects based on the saved YAML data, it is your responsibility to ensure that any “missing” variables are either not needed (in which case they may be ignored) or, if they are needed, that they are initialized with some meaningful value.

ob = Yclass.new( 100, "fred", [1,2,3] )
    # ...creates object with @num=100, @str="fred", @arr=[1,2,3]

yaml_ob = YAML.dump( ob )
    #...dumps to YAML only the @num and @arr data (omits @str)

ob2 = YAML.load( yaml_ob )
    #...creates ob2 from dumped data with @num=100, @arr=[1,2,3]
    # but without @str
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.179.100