On 5/20/05, Matthew Westcott <gasman / raww.org> wrote:
> Hi,
> Suppose (for reasons best known to myself) I had the following code:
> 
> require 'yaml'
> 
> class Squarer
>         attr_reader :num, :num_squared
> 
>         def initialize(num)
>                 @num = num
>                 @num_squared = num * num
>         end
> 
>         def to_yaml_properties
>                 # no need to store both num and num_squared...
>                 %w{ @num }
>         end
> end
> 
> s = Squarer.new(42)
> yaml_s = YAML.dump(s)
> 
> new_s = YAML.load(yaml_s)
> puts "new_s.num = #{new_s.num}"
> puts "new_s.num_squared = #{new_s.num_squared}"
> 
> 
> Is there any way I can hook up a bit of fixup code to set @num_squared
> appropriately after deserializing from YAML? If I were using Marshal,
> I'd just override the marshal_load method - what (if anything) is the
> YAML equivalent?
> 
> - Matthew
> 
> 

Well this solution doesn't involve yaml but...

class Squarer
         def num_squared
              @num_squared ||= @num * @num
         end
end

So it will calculate it only the first time you ask for it.