Alex Fenton
8/27/2006 10:52:00 PM
Paul Murton wrote:
> Hi,
>
> I have a whole load of objects which I would like to periodically dump
> as YAML. However, in order to save on resources, I would prefer to only
> dump those whose instance variables have changed since the last dump.
If you're interested in knowing whether instance variables have changed since a known point in the past (eg when you last dumped the object), rather than the moment they change, something like this might work:
module InstanceVariableSnapshooter
def clean!
@__snapshot__ = ivar_hash
end
def clean?
ivar_hash == @__snapshot__
end
def dirty?
not clean?
end
private
def ivar_hash
instance_variables.inject({}) do | iv_hash, i_var |
next iv_hash if i_var == '@__snapshot__'
iv_hash[i_var] = instance_variable_get(i_var)
iv_hash
end
end
end
Call clean! when the object is dumped to file, then call dirty? later to see if anything has changed. It's probably better to work via setter methods if you can, but this works direct with the variables.
Also, test whether this is less expensive than the dumping operation you're trying to avoid
alex