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