Class: GmHashWrapper::HashWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/gm_hash_wrapper/hash_wrapper.rb

Direct Known Subclasses

StrictHashWrapper

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body) ⇒ HashWrapper

Returns a new instance of HashWrapper.



6
7
8
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 6

def initialize(body)
  @body = ActiveSupport::HashWithIndifferentAccess.new(body)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 33

def method_missing meth, *args, &block
  if @body.has_key?(meth)
    if @body[meth].kind_of?(Hash)
      return HashWrapper.new(@body[meth])
    elsif @body[meth].kind_of?(Array)
      return @body[meth].map do |x|
        if x.kind_of?(Hash)
          HashWrapper.new(x)
        else
          x
        end
      end
    else
      return @body[meth]
    end
  end
  nil
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



4
5
6
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 4

def body
  @body
end

Instance Method Details

#as_json(options = {}) ⇒ Object



17
18
19
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 17

def as_json(options = {})
  @body
end

#each(&block) ⇒ Object



29
30
31
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 29

def each(&block)
  body.each &block
end

#nil?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 21

def nil?
  @body.keys.empty?
end

#present?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 25

def present?
  @body.keys.any?
end

#respond_to_missing?(meth, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 52

def respond_to_missing?(meth, include_private = false)
  @body.has_key?(meth) || super
end

#set_data(key, value) ⇒ Object



10
11
12
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 10

def set_data(key, value)
  @body[key.to_s] = value
end

#to_hObject



13
14
15
# File 'lib/gm_hash_wrapper/hash_wrapper.rb', line 13

def to_h
  @body
end