Class: SonOfHash

Inherits:
Object
  • Object
show all
Defined in:
lib/sonofhash.rb

Overview

Quacks like a Hash, but contains one additional method - commit()

Typical usage:

require 'rubygems'
require 'sonofhash'

parent = SonOfHash.new
child = parent.new_child

parent['name'] = 'Moondublin'
puts child['name']            # Moondublin

child['name'] = 'Lugrat'
puts parent['name']           # Moondublin

child.commit
puts parent['name']           # Lugrat

Instance Method Summary collapse

Constructor Details

#initialize(parent = {}) ⇒ SonOfHash

Returns a new instance of SonOfHash.



24
25
26
27
28
# File 'lib/sonofhash.rb', line 24

def initialize(parent={})
  @store = {}
  @deletions = Set.new
  @parent = parent
end

Instance Method Details

#[](key) ⇒ Object



36
37
38
39
40
# File 'lib/sonofhash.rb', line 36

def [](key)
  return nil if @deletions.member?(key)
  return @store[key] if @store.has_key?(key)
  @parent[key]
end

#[]=(key, value) ⇒ Object



42
43
44
# File 'lib/sonofhash.rb', line 42

def []=(key, value)
  @store[key] = value
end

#commitObject

Merges the changes of this object into its parent



61
62
63
64
65
66
67
68
69
# File 'lib/sonofhash.rb', line 61

def commit
  @store.each {|key, value| @parent[key] = value}
  @deletions.each {|key| @parent.delete(key)}
  
  # I want to clear the state here, but I don't know
  # a good spec for it yet
  # @store.clear
  # @deletions.clear
end

#delete(key) ⇒ Object



55
56
57
58
# File 'lib/sonofhash.rb', line 55

def delete(key)
  @deletions.add(key)
  return @store.delete(key)
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/sonofhash.rb', line 46

def has_key?(key)
  return member?(key)
end

#member?(key) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
# File 'lib/sonofhash.rb', line 50

def member?(key)
  return false if @deletions.member?(key);
  return @store.member?(key) || @parent.member?(key)
end

#new_childObject

Create a new child of this object. This is the primary way to record changes.



32
33
34
# File 'lib/sonofhash.rb', line 32

def new_child
  return SonOfHash.new(self)
end