Class: Billrb::Resource

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

Overview

Base class for API resources. Wraps the raw JSON attributes (camelCase string keys, as returned by the API) and exposes them as snake_case readers: resource.payment_term_id reads attributes.

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Resource

Returns a new instance of Resource.



14
15
16
# File 'lib/billrb/resource.rb', line 14

def initialize(attributes = {})
  @attributes = attributes.is_a?(Hash) ? attributes : {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



31
32
33
34
35
36
# File 'lib/billrb/resource.rb', line 31

def method_missing(name, *args)
  key = Util.camelize(name)
  return wrap(attributes[key]) if args.empty? && attributes.key?(key)

  super
end

Class Attribute Details

.resource_pathObject

Returns the value of attribute resource_path.



9
10
11
# File 'lib/billrb/resource.rb', line 9

def resource_path
  @resource_path
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



12
13
14
# File 'lib/billrb/resource.rb', line 12

def attributes
  @attributes
end

Instance Method Details

#[](key) ⇒ Object



18
19
20
# File 'lib/billrb/resource.rb', line 18

def [](key)
  wrap(attributes[Util.camelize(key)])
end

#idObject



22
23
24
# File 'lib/billrb/resource.rb', line 22

def id
  attributes["id"]
end

#inspectObject



42
43
44
# File 'lib/billrb/resource.rb', line 42

def inspect
  "#<#{self.class.name} #{attributes.inspect}>"
end

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

Returns:

  • (Boolean)


38
39
40
# File 'lib/billrb/resource.rb', line 38

def respond_to_missing?(name, include_private = false)
  attributes.key?(Util.camelize(name)) || super
end

#to_hObject

Raw attributes exactly as returned by the API (nested values stay hashes).



27
28
29
# File 'lib/billrb/resource.rb', line 27

def to_h
  attributes
end