lib/core/facets/hash/weave.rb in facets-2.1.3 vs lib/core/facets/hash/weave.rb in facets-2.2.0
- old
+ new
@@ -1,24 +1,15 @@
-# TITLE:
-#
-# Hash Weave Extension
-#
-# SUMMARY:
-#
-# Weave is a very uniqe hash operator. I is designed
-# to merge to complex hashes in according to sensible,
-# regular pattern. The effect is akin to inheritance.
-#
-# CREDITS:
-#
-# - Thomas Sawyer
-
class Hash
- # Weaves two hashes producing a new hash. The two hashes need
- # to be compatible according to the following rules for each node:
+ # Weave is a very uniqe hash operator. I is designed
+ # to merge to complex hashes in according to sensible,
+ # regular pattern. The effect is akin to inheritance.
#
+ # Two hashes are weaved together to produce a new hash.
+ # The two hashes need to be compatible according to the
+ # following rules for each node:
+ #
# <tt>
# hash, hash => hash (recursive +)
# hash, array => error
# hash, value => error
# array, hash => error
@@ -27,14 +18,27 @@
# value, hash => error
# value, array => array.unshift(valueB)
# value1, value2 => value2
# </tt>
#
- # Example:
+ # Here is a basic example:
#
- # # to do
+ # h1 = { :a => 1, :b => [ 1 ], :c => { :x => 1 } }
+ # => {:b=>[1], :c=>{:x=>1}, :a=>1}
#
+ # h2 = { :a => 2, :b => [ 2 ], :c => { :x => 2 } }
+ # => {:b=>[2], :c=>{:x=>2}, :a=>2}
+ #
+ # h1.weave(h2)
+ # => {:b=>[1, 2], :c=>{:x=>2}, :a=>2}
+ #
+ # Weave follows the most expected pattern of unifying two complex
+ # hashes. It is especially useful for implementing overridable
+ # configuration schemes.
+ #
+ # CREDIT: Thomas Sawyer
+
def weave(h)
raise ArgumentError, "Hash expected" unless h.kind_of?(Hash)
s = self.clone
h.each { |k,node|
node_is_hash = node.kind_of?(Hash)
@@ -73,29 +77,5 @@
}
s
end
end
-
-
-# _____ _
-# |_ _|__ ___| |_
-# | |/ _ \/ __| __|
-# | | __/\__ \ |_
-# |_|\___||___/\__|
-#
-=begin test
-
- require 'test/unit'
-
- class TestHashWeave < Test::Unit::TestCase
-
- def test_weave
- b = { :a=>1, :b=>[1,2,3], :c=>{ :x=>'X' } }
- c = { :a=>2, :b=>[4,5,6], :c=>{ :x=>'A', :y => 'B' } }
- r = { :a=>2, :b=>[1,2,3,4,5,6], :c=>{ :x => 'A', :y => 'B' } }
- assert_equal( r, b.weave(c) )
- end
-
- end
-
-=end