Sha256: 9f54c36a53dbefa3301ec95b00f1e4fdc16a2a0fbd59b4e930d2c4c47da3c838

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

require 'httparty'
require 'multi_json'
require 'hashie'
require 'time'
require 'securerandom'

require "datarank/topics"
require "datarank/comments"

module Datarank
  class Client
    include HTTParty

    include Datarank::Client::Topics
    include Datarank::Client::Comments

    BASE_URI = 'https://api.datarank.com'

    def initialize(api_key=nil, api_version=nil, options={})
      @api_key = api_key
      @api_version = api_version ? api_version : "v1";

      # defaults
      options[:base_uri] ||= BASE_URI
      @base_uri = options[:base_uri]
      options[:format]   ||= :json
      options.each do |k,v|
        self.class.send k, v
      end
    end

    # Wrappers for the main HTTP verbs

    def get(path, options={})
      http_verb :get, path, options
    end

    def post(path, options={})
      http_verb :post, path, options
    end

    def put(path, options={})
      http_verb :put, path, options
    end

    def delete(path, options={})
      http_verb :delete, path, options
    end

    def http_verb(verb, path, options={})

      if [:get, :delete].include? verb
        request_options = {}
        path = "#{path}?#{URI.encode_www_form(options)}" if !options.empty?
      else
        request_options = {body: options.to_json}
      end

      headers = {
        'Authorization' => @api_key,
        "Content-Type" => "application/json",
        "Accept" => "application/vnd.datarank.#{@api_version}+json"
      }

      request_options[:headers] = headers

      r = self.class.send(verb, path, request_options)
      hash = Hashie::Mash.new(JSON.parse(r.body))
      raise Error.new(hash.error) if hash.error
      raise Error.new(hash.errors.join(", ")) if hash.errors
      hash
    end

    class Error < StandardError; end

    private

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
datarank-0.2 lib/datarank/client.rb