Sha256: 939dfda533079188993bdec27097aa2e18ec428da0ef030d8148cbbd378145f2

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

=begin rdoc

= 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

  require 'raspberry/new/snapshot'

  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
  
== TODO

* Perhaps extend to offer multiple depths.
* Should key consitancy be enforced? Currently
  Struct's will have symobl keys while other classes
  will have string keys in the form of "@name".
* Add other core classes.

== History

* 20005.04.11 Passed basic test.

==

=end

class Object
  def take_snapshot
    snap = Hash.new
    instance_variables.each do |iv|
      snap[iv] = instance_variable_get(iv)
    end
    snap
  end

  def apply_snapshot(snap)
    instance_variables.each do |iv|
      instance_variable_set(iv, snap[iv])
    end
  end
end

class Array
  def take_snapshot
    dup
  end

  def apply_snapshot(snap)
    replace(snap)
  end
end

class String
  def take_snapshot
    dup
  end

  def apply_snapshot(snap)
    replace(snap)
  end
end

# Struct snapshots look a bit different
# since they don't use instance variables.
class Struct
  def take_snapshot
    snap = Hash.new
    each_pair { |k,v| snap[k] = v }
    snap
  end

  def apply_snapshot(snap)
    snap.each_pair{ |k,v| send( "#{k}=", v ) } 
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
carats-0.3.0 lib/carat/snapshot.rb