Class: HelloSign::Resource::BaseResource

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

Overview

Stores 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.



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

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



72
73
74
# File 'lib/hello_sign/resource/base_resource.rb', line 72

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.



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

def data
  @data
end

#headersObject (readonly)

Returns the value of attribute headers.



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

def headers
  @headers
end

#raw_dataObject (readonly)

Returns the value of attribute raw_data.



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

def raw_data
  @raw_data
end

#warningsObject (readonly)

Returns the value of attribute warnings.



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

def warnings
  @warnings
end