Class: Codat::BaseModel

Inherits:
Object
  • Object
show all
Defined in:
lib/codat/base_model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json: {}, key_transformer: Camelizer) ⇒ BaseModel

Sets all the instance variables by reading the JSON from Codat and converting the keys from camelCase to snake_case, as it’s the standard in Ruby.



52
53
54
55
56
# File 'lib/codat/base_model.rb', line 52

def initialize(json: {}, key_transformer: Camelizer)
  self.class.attributes.each do |attr|
    send("#{attr}=", json[key_transformer.transform(attr)])
  end
end

Class Method Details

.attributes(*attributes) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/codat/base_model.rb', line 25

def attributes(*attributes)
  @attributes ||= []

  return @attributes unless attributes

  attr_accessor(*attributes)

  @attributes += attributes
end

.format_url(url, params) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/codat/base_model.rb', line 35

def format_url(url, params)
  formatted = url.dup.strip

  params.each { |key, value| formatted.sub!(":#{key}", value) }

  formatted
end

.get(path, params = {}) ⇒ Object

Raises:



9
10
11
12
13
14
15
# File 'lib/codat/base_model.rb', line 9

def get(path, params = {})
  result = Codat.client.get(path.strip, params)

  raise APIKeyError, result.body[:error] if result.status == 401

  result
end

.post(path, params = {}) ⇒ Object

Raises:



17
18
19
20
21
22
23
# File 'lib/codat/base_model.rb', line 17

def post(path, params = {})
  result = Codat.client.post(path.strip, params)

  raise APIKeyError, result.body[:error] if result.status == 401

  result
end

.successful_response?(result) ⇒ Boolean

As per Codat API doc docs.codat.io/reference/errors

Returns:

  • (Boolean)


45
46
47
# File 'lib/codat/base_model.rb', line 45

def successful_response?(result)
  result.status < 400
end

Instance Method Details

#format_url(url, params) ⇒ Object



66
67
68
# File 'lib/codat/base_model.rb', line 66

def format_url(url, params)
  self.class.format_url(url, params)
end

#get(path, params = {}) ⇒ Object



58
59
60
# File 'lib/codat/base_model.rb', line 58

def get(path, params = {})
  self.class.get(path, params)
end

#post(path, params = {}) ⇒ Object



62
63
64
# File 'lib/codat/base_model.rb', line 62

def post(path, params = {})
  self.class.post(path, params)
end