Snapshot
A lightweight single-depth object state capture. The take_snapshot method reads the object‘s state, which is generally it‘s collection of instance variables, and returns them in a hash. The state can be restored with apply_snapshot.
Usage
Customer = Struct.new("Customer", :name, :address, :zip) joe = Customer.new( "Joe Pitare", "1115 Lila Ln.", 47634 ) # simple transactions joe_snap = joe.take_snapshot begin do_something_with( joe ) rescue joe.apply_snapshot( joe_snap ) end joe_snap[:name] => "Joe Pitare" joe_snap[:address] => "1115 Lila Ln." joe_snap[:zip] => 47634
Details
Class Snapshot simply represents a collection of objects from which snapshots were taken via their methods take_snapshot. It provides methods to add an object to a snapshot (Snapshot#add) as well as to restore all objects of the snapshot to their state stored in the snapshot (method Snapshot#restore).
In Wee, this class is used to backtracking the state of components (or decorations/presenters). Components that want an undo-facility to be implemented (triggered for example by a browsers back-button), have to overwrite the Wee::Component#backtrack_state method.
[ show source ]
# File lib/more/facets/snapshot.rb, line 109 def initialize @objects = Hash.new end
[ show source ]
# File lib/more/facets/snapshot.rb, line 113 def add(object) oid = object.object_id @objects[oid] = [object, object.take_snapshot] unless @objects.include?(oid) end
[ show source ]
# File lib/more/facets/snapshot.rb, line 118 def restore @objects.each_value do |object, value| object.restore_snapshot(value) end end