class Devpad::Client

Attributes

api_format[RW]
api_version[RW]
endpoint[RW]
user_agent[RW]
user_api_key[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/devpad/client.rb, line 11
def initialize(options = {})
  Devpad::Configuration::VALID_CLIENT_ATTRIBUTES.each do |key|
    send("#{key}=", options[key])
  end
end

Public Instance Methods

connection(options = {}) click to toggle source
# File lib/devpad/client.rb, line 17
def connection(options = {})
  api_version = options.delete(:api_version) || self.api_version
  api_format  = options.delete(:api_format)  || :json

  options = {
    url: self.endpoint,
    params: {},
    headers: {
      accept: "application/vnd.devpad.v#{api_version}+#{api_format}",
      user_agent: self.user_agent,
      x_gem_version: Devpad::VERSION,
    }.merge(options.delete(:headers) || {})
  }.merge(options)

  Faraday.new(options) do |c|
    c.request :multipart
    c.request :url_encoded
    c.adapter :net_http
  end
end
download(endpoint, to, params = {}) click to toggle source
# File lib/devpad/client.rb, line 38
def download(endpoint, to, params = {})
  response = connection.method(:get).call(endpoint, params)
  open(to, "wb") do |file|
    file.write(response.body)
  end
end
get(endpoint, params = {}) click to toggle source
# File lib/devpad/client.rb, line 45
def get(endpoint, params = {})
  json_response(:get, endpoint_with_host(endpoint), params)
end
post(endpoint, params = {}) click to toggle source
# File lib/devpad/client.rb, line 49
def post(endpoint, params = {})
  json_response(:post, endpoint_with_host(endpoint), params)
end

Private Instance Methods

endpoint_with_host(path) click to toggle source
# File lib/devpad/client.rb, line 72
def endpoint_with_host(path)
  "#{endpoint}#{path}"
end
json_response(method, endpoint, params = {}) click to toggle source
# File lib/devpad/client.rb, line 63
def json_response(method, endpoint, params = {})
  json = JSON.parse(make_request(method, endpoint, params).body)
  if json['errors']
    puts json['errors'].map { |item| item['detail'] }.join("\n")
    exit!
  end
  json
end
make_request(method, endpoint, params = {}) click to toggle source
# File lib/devpad/client.rb, line 55
def make_request(method, endpoint, params = {})
  connection.method(method).call(endpoint, params) do |request|
    if self.user_api_key.present?
      request.headers['Authorization'] = self.user_api_key
    end
  end
end