Class: Pnut::Client

Inherits:
Object
  • Object
show all
Includes:
Posts
Defined in:
lib/pnut.rb

Instance Method Summary collapse

Methods included from Posts

#global, #unified

Constructor Details

#initialize(authorization_token: nil) ⇒ Client

Returns a new instance of Client.



12
13
14
15
# File 'lib/pnut.rb', line 12

def initialize(authorization_token: nil)
  @token = authorization_token
  @connection = Faraday.new("https://api.pnut.io/")
end

Instance Method Details

#request(endpoint, method: "GET", params: nil, data: nil, raw_response: false, json: true) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pnut.rb', line 17

def request(endpoint, method: "GET", params: nil, data: nil, raw_response: false, json: true)
  prepared_endpoint = "/v0#{endpoint}"

  if params
    uri = Addressable::URI.new
    uri.query_values = params
    prepared_endpoint += "?#{uri.query}"
  end

  response = @connection.send(method.downcase.to_sym, prepared_endpoint) do |req|
    req.url prepared_endpoint

    req.headers["Content-Type"] = "application/json" if json
    req.headers["Authorization"] = "Bearer #{@token}" if @token

    if json
      req.body = data.to_json if data
    else
      req.body = data if data
    end
  end

  raw_response ? response.body : JSON.parse(response.body, object_class: OpenStruct)
end