Class: Truelayer::BaseModel

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ BaseModel

Returns a new instance of BaseModel.


35
36
37
38
39
# File 'lib/truelayer/base_model.rb', line 35

def initialize(attributes = {})
  attributes.each do |attr, value|
    public_send("#{attr}=", value)
  end
end

Class Method Details

.attribute_aliases(aliases = nil) ⇒ Object


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

def attribute_aliases(aliases = nil)
  @attribute_aliases ||= {}

  return @attribute_aliases unless aliases

  @attribute_aliases.merge!(aliases)
end

.attributes(*attributes) ⇒ Object


6
7
8
9
10
11
12
13
14
# File 'lib/truelayer/base_model.rb', line 6

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

  return @attributes unless attributes

  attr_accessor(*attributes)

  @attributes += attributes
end

.build(json: {}) ⇒ Object

Sets all the instance variables by reading the JSON from API


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

def build(json: {})
  new.tap do |record|
    attributes.each do |attr|
      key = attribute_aliases.key?(attr) ? attribute_aliases[attr] : attr
      record.public_send("#{attr}=", json[key])
    end
  end
end

Instance Method Details

#as_jsonObject


41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/truelayer/base_model.rb', line 41

def as_json
  self.class.attributes.each_with_object({}) do |attr, hash|
    value = public_send(attr)

    value = value.as_json if value.respond_to?(:as_json)
    if value.is_a?(Array)
      value = value.map { |v| v.respond_to?(:as_json) ? v.as_json : v }
    end
    value = value.iso8601 if value.respond_to?(:iso8601)

    hash[attr] = value
  end
end