require 'httparty' require 'multi_json' require 'hashie' require 'time' require 'securerandom' require "datarank/comments" require "datarank/datasources" require "datarank/fizzle" require "datarank/live" require "datarank/locations" require "datarank/reach" require "datarank/retailers" require "datarank/sentiment" require "datarank/themes" require "datarank/topics" require "datarank/volume" require "datarank/wordcloud" require "datarank/search" module Datarank class Client include HTTParty include Datarank::Client::Topics include Datarank::Client::Comments include Datarank::Client::Datasources include Datarank::Client::Fizzle include Datarank::Client::Live include Datarank::Client::Locations include Datarank::Client::Reach include Datarank::Client::Retailers include Datarank::Client::Sentiment include Datarank::Client::Themes include Datarank::Client::Volume include Datarank::Client::Wordcloud include Datarank::Client::Search 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) # FIXME: raise errors on actual error packages parsed_json = JSON.parse(r.body) if parsed_json.is_a? Array parsed_json = {objects: parsed_json} end hash = Hashie::Mash.new(parsed_json) 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