Class: Revolut::Resource

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Resource

Returns a new instance of Resource.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/revolut/resources/resource.rb', line 95

def initialize(attrs = {})
  @_raw = attrs

  attrs.each do |key, value|
    if self.class.skip_coertion_for.include?(key.to_sym)
      instance_variable_set(:"@#{key}", value)
    else
      coerce_class = self.class.coerce_with[key.to_sym] || Revolut::Resource
      coerced_value = if value.is_a?(Hash)
        coerce_class.new(value)
      elsif value.is_a?(Array)
        value.map do |v|
          v.is_a?(Hash) ? coerce_class.new(v) : v
        end
      else
        value
      end
      instance_variable_set(:"@#{key}", coerced_value)
    end
  end

  instance_variables.each { |iv| self.class.send(:attr_accessor, iv.to_s[1..].to_sym) }
end

Class Method Details

.coerce_with(**attrs) ⇒ Object



56
57
58
# File 'lib/revolut/resources/resource.rb', line 56

def coerce_with(**attrs)
  @coerce_with ||= attrs
end

.create(**attrs) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/revolut/resources/resource.rb', line 4

def create(**attrs)
  check_not_allowed

  response = http_client.post("/#{resource_name}", data: attrs)

  body = response.body

  return body.map(&self) if body.is_a?(Array)

  new(body)
end

.delete(id) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/revolut/resources/resource.rb', line 40

def delete(id)
  check_not_allowed

  http_client.delete("/#{resource_name}/#{id}")

  true
end

.http_clientObject



60
61
62
# File 'lib/revolut/resources/resource.rb', line 60

def http_client
  @http_client ||= Revolut::Client.instance
end

.listObject



32
33
34
35
36
37
38
# File 'lib/revolut/resources/resource.rb', line 32

def list(**)
  check_not_allowed

  response = http_client.get("/#{resources_name}", **)

  response.body.map(&self)
end

.retrieve(id) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/revolut/resources/resource.rb', line 16

def retrieve(id)
  check_not_allowed

  response = http_client.get("/#{resource_name}/#{id}")

  new(response.body)
end

.skip_coertion_for(*attrs) ⇒ Object



52
53
54
# File 'lib/revolut/resources/resource.rb', line 52

def skip_coertion_for(*attrs)
  @skip_coertion_for ||= attrs
end

.to_procObject



48
49
50
# File 'lib/revolut/resources/resource.rb', line 48

def to_proc
  ->(attrs) { new(attrs) }
end

.update(id, **attrs) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/revolut/resources/resource.rb', line 24

def update(id, **attrs)
  check_not_allowed

  response = http_client.patch("/#{resource_name}/#{id}", data: attrs)

  new(response.body)
end

Instance Method Details

#to_jsonObject



119
120
121
# File 'lib/revolut/resources/resource.rb', line 119

def to_json
  @_raw.to_json
end