Class: Base::Endpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/base/endpoint.rb

Overview

The base class for an endpoint.

It handles request lifecycle and error handling and offers a Faraday::Connection

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token:, url:) ⇒ Endpoint

Initializes the endpoint with an access_token and url.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/base/endpoint.rb', line 31

def initialize(access_token:, url:)
  @connection =
    Faraday.new(
      "#{url}/v1/#{path}/",
      headers: { 'Authorization' => "Bearer #{access_token}" }
    ) do |conn|
      conn.request :multipart
      conn.request :url_encoded

      conn.use RaiseError
      conn.use Faraday::Adapter::NetHttp
    end
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



27
28
29
# File 'lib/base/endpoint.rb', line 27

def connection
  @connection
end

#pathObject (readonly)

Returns the value of attribute path.



28
29
30
# File 'lib/base/endpoint.rb', line 28

def path
  @path
end

Instance Method Details

#io(body) ⇒ Object



62
63
64
65
66
67
68
69
70
71
# File 'lib/base/endpoint.rb', line 62

def io(body)
  case body
  when IO
    body
  when String
    StringIO.new(body)
  else
    IO.try_convert(body)
  end
end

#parse(body) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/base/endpoint.rb', line 54

def parse(body)
  object = JSON.parse(body, object_class: OpenStruct)

  object.created_at = Time.rfc2822(object.created_at) if object.created_at

  object
end

#requestObject

Handles errors that happen in its block.



46
47
48
49
50
51
52
# File 'lib/base/endpoint.rb', line 46

def request
  yield
rescue Unauthorized, InvalidRequest => e
  raise e
rescue StandardError => e
  raise UnkownError.new(e)
end