module Mango

Attributes

api_base[RW]
api_key[RW]

Public Class Methods

request(method, url, api_key=nil, params={}, headers={}) click to toggle source
# File lib/mango.rb, line 28
def self.request(method, url, api_key=nil, params={}, headers={})
  method = method.to_sym

  url = @api_base + url

  unless api_key ||= @api_key
    raise Error.new('No API key provided')
  end

  payload = JSON.generate(params) if method == :post || method == :patch
  params = nil unless method == :get

  headers = {
    :params => params,
    :content_type => 'application/json'
  }.merge(headers)

  options = {
    :headers => headers,
    :user => api_key,
    :method => method,
    :url => url,
    :payload => payload
  }

  begin
    response = execute_request(options)
    return {} if response.code == 204 and method == :delete
    JSON.parse(response.body, :symbolize_names => true)
  rescue RestClient::Exception => e
    handle_errors e
  end
end

Private Class Methods

execute_request(options) click to toggle source
# File lib/mango.rb, line 64
def self.execute_request(options)
  RestClient::Request.execute(options)
end
handle_errors(exception) click to toggle source
# File lib/mango.rb, line 68
def self.handle_errors exception
  body = JSON.parse exception.http_body
  raise Error.new(exception.to_s, body['errors'])
end