module Localytics

Attributes

api_key[RW]
api_secret[RW]

Public Class Methods

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

  url = api_base + url

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

  unless api_secret ||= @api_secret
    raise Error.new('No API secret provided')
  end

  unless method == :get
    payload = JSON.generate(params)
    params  = nil
  end

  auth = 'Basic ' + Base64.strict_encode64("#{api_key}:#{api_secret}")

  headers = {
      :params        => params,
      :content_type  => 'application/json',
      :accept        => 'application/json',
      :authorization => auth

  }.merge(headers)

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

  begin
    return_hash = {}
    response    = execute_request(options)
    return return_hash  if  response.code == 204 && method == :delete

    if response.body && !response.body.empty?
      # Don't try to call JSON.parse on empty response body.
      return_hash = JSON.parse(response.body, :symbolize_names => true)
    end
    return return_hash

  rescue RestClient::Exception => e
    handle_errors e
  end
end

Private Class Methods

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