class MarbleApiClient::Client

Main class for sending HTTP requests to a URL. Requests are sent using request and response objects crafted for each action. Headers can be provided to the Proxy as default headers for all requests

Public Class Methods

new(base_url, headers: {}) click to toggle source
# File lib/marble_api_client/client.rb, line 15
def initialize(base_url, headers: {})
  raise ArgumentError, 'Base URL is not valid' unless base_url_valid?(base_url)

  @base_url = base_url
  @headers = { 'Content-Type': 'application/json' }.merge(headers)
  freeze
end

Public Instance Methods

create(path, create_request: Requests::Create.new, headers: {}) click to toggle source
# File lib/marble_api_client/client.rb, line 23
def create(path, create_request: Requests::Create.new, headers: {})
  response = send_request(path, Requests::Create.make(create_request), headers, 'create')
  Responses.parse_response(response, Responses::CREATE_ACTION)
end
index(path, index_request: Requests::Index.new, headers: {}) click to toggle source
# File lib/marble_api_client/client.rb, line 28
def index(path, index_request: Requests::Index.new, headers: {})
  response = send_request(path, Requests::Index.make(index_request), headers, 'index')
  Responses.parse_response(response, Responses::INDEX_ACTION)
end

Private Instance Methods

base_url_valid?(url) click to toggle source
# File lib/marble_api_client/client.rb, line 59
def base_url_valid?(url)
  uri = URI.parse(url)
  uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
rescue URI::InvalidURIError
  false
end
join_path(path, action) click to toggle source
# File lib/marble_api_client/client.rb, line 47
def join_path(path, action)
  if path[-1] == '/'
    URI.join(@base_url, path + action)
  else
    URI.join(@base_url, path + '/' + action)
  end
end
send_request(path, request_object, headers, action) click to toggle source
# File lib/marble_api_client/client.rb, line 35
def send_request(path, request_object, headers, action)
  uri = join_path(path, action)
  merged_headers = @headers.merge(headers)

  Net::HTTP.start(uri.host, uri.port, use_ssl: ssl?(uri)) do |http|
    request = Net::HTTP::Post.new(uri.request_uri)
    merged_headers.each { |key, value| request.add_field(key.to_s, value.to_s) }
    request.body = request_object.request_body
    http.request(request)
  end
end
ssl?(uri) click to toggle source
# File lib/marble_api_client/client.rb, line 55
def ssl?(uri)
  uri.scheme == 'https'
end