Class: StrixRuby::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/strix_ruby/connection.rb

Overview

HTTP connection wrapper using Faraday

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url:) ⇒ Connection

Returns a new instance of Connection.



11
12
13
14
# File 'lib/strix_ruby/connection.rb', line 11

def initialize(base_url:)
  @base_url = base_url.chomp("/")
  @connection = build_connection
end

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



9
10
11
# File 'lib/strix_ruby/connection.rb', line 9

def base_url
  @base_url
end

Instance Method Details

#get(path, params: {}, headers: {}) ⇒ Hash

Perform a GET request

Parameters:

  • path (String)

    the API path

  • params (Hash) (defaults to: {})

    query parameters

  • headers (Hash) (defaults to: {})

    additional headers

Returns:

  • (Hash)

    parsed JSON response



21
22
23
24
25
26
27
28
29
30
# File 'lib/strix_ruby/connection.rb', line 21

def get(path, params: {}, headers: {})
  response = @connection.get(path) do |req|
    req.params = params unless params.empty?
    headers.each { |key, value| req.headers[key] = value }
  end

  handle_response(response)
rescue Faraday::ClientError => e
  handle_faraday_error(e)
end

#post_form(path, body: {}, headers: {}) ⇒ Hash

Perform a POST request with form data

Parameters:

  • path (String)

    the API path

  • body (Hash) (defaults to: {})

    form data

  • headers (Hash) (defaults to: {})

    additional headers

Returns:

  • (Hash)

    parsed JSON response



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/strix_ruby/connection.rb', line 37

def post_form(path, body: {}, headers: {})
  response = @connection.post(path) do |req|
    req.headers["Content-Type"] = "application/x-www-form-urlencoded"
    headers.each { |key, value| req.headers[key] = value }
    req.body = URI.encode_www_form(body)
  end

  handle_response(response)
rescue Faraday::ClientError => e
  handle_faraday_error(e)
end