Class: HelloSign::Resource::BaseResource

Inherits:
Object
  • Object
show all
Defined in:
lib/hello_sign/resource/base_resource.rb

Overview

Store the value of a hash. Use missing_method to create method to access it like an object

Author:

  • hellosign

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, key = nil) ⇒ HelloSign::Resource::BaseResource

recursively convert hash data into BaseResource.

Parameters:

  • hash (Hash)

    data of the resource

  • key (String) (defaults to: nil)

    (nil) key of the hash, point to where resource data is. If nil then the hash itself



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/hello_sign/resource/base_resource.rb', line 44

def initialize(hash, key=nil)
  @headers = hash[:headers]
  @raw_data = key ? hash[:body][key] : hash
  if hash[:body]
    @warnings = hash[:body]['warnings'] ? hash[:body]['warnings'] : nil
  end
  
  @data = @raw_data.inject({}) do |data, (key, value)|
    data[key.to_s] = if value.is_a? Hash
      value = BaseResource.new(value)
    elsif ((value.is_a? Array) && (value[0].is_a? Hash))
      value = value.map {|v| BaseResource.new(v)}
    else
      value
    end
    data
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method) ⇒ Object

Magic method, give class dynamic methods based on hash keys.

If initialized hash has a key which matches the method name, return value of that key.

Otherwise, return nil

Examples:

resource  = BaseResource.new :email_address => "[email protected]"
resource.email_address # =>  "[email protected]"
resource.not_in_hash_keys # => nil

Parameters:

  • method (Symbol)

    Method’s name



76
77
78
# File 'lib/hello_sign/resource/base_resource.rb', line 76

def method_missing(method)
  @data.key?(method.to_s) ? @data[method.to_s] : nil
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



35
36
37
# File 'lib/hello_sign/resource/base_resource.rb', line 35

def data
  @data
end

#headersObject (readonly)

Returns the value of attribute headers.



35
36
37
# File 'lib/hello_sign/resource/base_resource.rb', line 35

def headers
  @headers
end

#raw_dataObject (readonly)

Returns the value of attribute raw_data.



35
36
37
# File 'lib/hello_sign/resource/base_resource.rb', line 35

def raw_data
  @raw_data
end

#warningsObject (readonly)

Returns the value of attribute warnings.



35
36
37
# File 'lib/hello_sign/resource/base_resource.rb', line 35

def warnings
  @warnings
end