Class: Hash

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

Direct Known Subclasses

ActiveConfig::HashConfig

Instance Method Summary collapse

Instance Method Details

#weave(h, dont_clobber = true) ⇒ Object

source: rubyforge.org/projects/facets/ version: 1.7.46 license: Ruby License NOTE: remove this method if the Facets gem is installed. BUG: weave is destructive to values in the source hash that are arrays!

(this is acceptable for our use as the basis for weave!)

Weaves two hashes producing 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
array, array => array + array
array, value => array << value
value, hash => error
value, array => array.unshift(valueB)
valueA, valueB => valueB
</tt>

Example:

# to do

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/active_config/hash_weave.rb', line 29

def weave(h, dont_clobber=true)
  return self unless h
  raise ArgumentError, "Hash expected" unless h.kind_of?(Hash)
  s = self.dup # self.clone does not remove freeze!
  h.each { |k,node|
    node_is_hash = node.kind_of?(Hash)
    node_is_array = node.kind_of?(Array)
    if s.has_key?(k)
      self_node_is_hash = s[k].kind_of?(Hash)
      self_node_is_array = s[k].kind_of?(Array)
      if self_node_is_hash
        if node_is_hash
          s[k] = s[k].weave(node, dont_clobber)
        elsif node_is_array
          dont_clobber ? raise(ArgumentError, "{} <= [] is a tad meaningless") : s[k] = node
        else
          s[k] = node
        end
      elsif self_node_is_array
        if node_is_hash
          dont_clobber ? s[k] = s[k] << node : s[k] = node
        elsif node_is_array
          dont_clobber ? s[k] += node : s[k] = node
        else
          dont_clobber ? s[k] = s[k] << node : s[k] = node
        end
      else
        if node_is_hash
          s[k] = node
        elsif node_is_array
          dont_clobber ? s[k].unshift( node ) : s[k] = node
        else
          s[k] = node
        end
      end
    else
      s[k] = node
    end
  }
  s
end

#weave!(h, dont_clobber = true) ⇒ Object



70
# File 'lib/active_config/hash_weave.rb', line 70

def weave!(h, dont_clobber = true) self.merge! self.weave(h, dont_clobber) end