Class: SonOfHash
- Inherits:
-
Object
- Object
- SonOfHash
- 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
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
-
#commit ⇒ Object
Merges the changes of this object into its parent.
- #delete(key) ⇒ Object
- #has_key?(key) ⇒ Boolean
-
#initialize(parent = {}) ⇒ SonOfHash
constructor
A new instance of SonOfHash.
- #member?(key) ⇒ Boolean
-
#new_child ⇒ Object
Create a new child of this object.
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 |
#commit ⇒ Object
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
46 47 48 |
# File 'lib/sonofhash.rb', line 46 def has_key?(key) return member?(key) end |
#member?(key) ⇒ 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 |