Class: EasyLlama::Client::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/easyllama/api.rb

Overview

This class provides methods for interacting with the Easy Llama API.

Direct Known Subclasses

LearnerTrainings, Learners, Locations, OAuth, Trainings

Constant Summary collapse

DEFAULT_URI_BASE =
'https://api.easyllama.com/api/'
DEFAULT_API_VERSION =
'v1'

Instance Method Summary collapse

Constructor Details

#initialize(token) ⇒ String

Initializes the API client.

Parameters:

  • token (String)

    The token.



14
15
16
17
18
# File 'lib/easyllama/api.rb', line 14

def initialize(token)
  @token = token

  super()
end

Instance Method Details

#parse_response!(response, key = nil) ⇒ Object

Parses the response body. If the response is successful, returns the value for the key. If the response is unsuccessful, returns an error code and message.

Parameters:

  • response (Net::HTTPResponse)

    The HTTP response.

  • key (String) (defaults to: nil)

    The key to retrieve from the response body.

Returns:

  • (Object)

    The empty hash, parsed response body, value corresponding to the key or error code and message.



41
42
43
44
45
46
47
48
49
50
# File 'lib/easyllama/api.rb', line 41

def parse_response!(response, key = nil)
  if response.is_a?(Net::HTTPSuccess)
    return {} if response.body.nil?
    return JSON.parse(response.body) if key.nil?

    JSON.parse(response.body)[key]
  else
    { 'code' => response.code, 'error' => response.message }
  end
end

#send_request(path: nil, method: :get, body: nil) ⇒ Net::HTTPResponse

Sends an HTTP request to the specified path.

Parameters:

  • path (String) (defaults to: nil)

    The path of the API endpoint.

  • method (Symbol) (defaults to: :get)

    The HTTP method (:get, :post, :put, :patch, :delete).

  • body (Hash) (defaults to: nil)

    The request body (optional).

Returns:

  • (Net::HTTPResponse)

    The HTTP response.

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
# File 'lib/easyllama/api.rb', line 26

def send_request(path: nil, method: :get, body: nil)
  raise ArgumentError, 'Please provide EasyLlama::Client.api_token' if @token.nil?

  uri = build_uri(path)
  request = build_request(uri, method, body)
  execute_request(uri, request)
end