Class: SuperHash

Inherits:
Delegator
  • Object
show all
Defined in:
lib/super_hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ SuperHash

Returns a new instance of SuperHash.



7
8
9
10
11
# File 'lib/super_hash.rb', line 7

def initialize(attributes = {})
  self.attributes = ActiveSupport::HashWithIndifferentAccess.new attributes
  self.coerce!
  self.define_key_methods!
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



5
6
7
# File 'lib/super_hash.rb', line 5

def attributes
  @attributes
end

Instance Method Details

#__getobj__Object



36
37
38
# File 'lib/super_hash.rb', line 36

def __getobj__
  @attributes
end

#coerce!Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/super_hash.rb', line 13

def coerce!
  self.attributes.each do |key, value|
    case value
    when Hash
      self.attributes[key] = SuperHash.new value
    when Array
      value.each_with_index do |array_value, index|
        value[index] = SuperHash.new(array_value) if array_value.is_a?(Hash)
      end
    end
  end
end

#define_key_methods!Object



26
27
28
29
30
31
32
33
34
# File 'lib/super_hash.rb', line 26

def define_key_methods!
  self.attributes.each do |key, value|
    unless self.respond_to?(key.to_sym)
      self.class.send(:define_method, key.to_sym) do
        self.attributes[key]
      end
    end
  end
end

#to_json(options = {}) ⇒ Object



40
41
42
# File 'lib/super_hash.rb', line 40

def to_json(options={})
  @attributes.to_json options
end