]> git.donarmstrong.com Git - dsa-puppet.git/blob - 3rdparty/modules/aviator/lib/puppet/feature/aviator/core/utils/hashish.rb
add aimonb/aviator to 3rdparty
[dsa-puppet.git] / 3rdparty / modules / aviator / lib / puppet / feature / aviator / core / utils / hashish.rb
1 require 'json'
2
3 # Hash-ish!
4 #
5 # This class is implemented using composition rather than inheritance so
6 # that we have control over what operations it exposes to peers.
7 class Hashish
8   include Enumerable
9
10   def initialize(hash={})
11     @hash = hash.dup
12     stringify_keys
13     hashishify_values
14   end
15
16   def ==(other_obj)
17     other_obj.class == self.class &&
18     other_obj.hash == self.hash
19   end
20
21   def [](key)
22     @hash[normalize(key)]
23   end
24
25   def []=(key, value)
26     @hash[normalize(key)] = value
27   end
28
29   def dup
30     Hashish.new(JSON.parse(@hash.to_json))
31   end
32
33   def each(&block)
34     @hash.each(&block)
35   end
36
37   def empty?
38     @hash.empty?
39   end
40
41   def has_key?(name)
42     @hash.has_key? normalize(name)
43   end
44
45   def hash
46     @hash
47   end
48
49   def keys
50     @hash.keys
51   end
52
53   def length
54     @hash.length
55   end
56
57   def merge(other_hash)
58     Hashish.new(@hash.merge(other_hash))
59   end
60
61   def merge!(other_hash)
62     @hash.merge! other_hash
63     self
64   end
65
66   def to_json(obj)
67     @hash.to_json(obj)
68   end
69
70   def to_s
71     str = "{"
72     @hash.each do |key, value|
73       if value.kind_of? String
74         value = "'#{value}'"
75       elsif value.nil?
76         value = "nil"
77       elsif value.kind_of? Array
78         value = "[#{value.join(", ")}]"
79       end
80
81       str += " #{key}: #{value},"
82     end
83
84     str = str[0...-1] + " }"
85     str
86   end
87
88   private
89
90   # Hashishify all the things!
91   def hashishify_values
92     @hash.each do |key, value|
93       if @hash[key].kind_of? Hash
94         @hash[key] = Hashish.new(value)
95       elsif @hash[key].kind_of? Array
96         @hash[key].each_index do |index|
97           element = @hash[key][index]
98           if element.kind_of? Hash
99             @hash[key][index] = Hashish.new(element)
100           end
101         end
102       end
103     end
104   end
105
106
107   def normalize(key)
108     if @hash.has_key? key
109       key
110     elsif key.is_a? Symbol
111       key.to_s
112     else
113       key
114     end
115   end
116
117
118   def stringify_keys
119     keys = @hash.keys
120     keys.each do |key|
121       if key.is_a? Symbol
122         @hash[key.to_s] = @hash.delete(key)
123       end
124     end
125   end
126
127 end