require 'rest-client' require_relative 'utils' require_relative 'response' module Fanforce::Api include Fanforce::Api::Utils include Fanforce::Errors def self.included(base) base.extend(self) end def initialize(arg={}) if arg.is_a?(Hash) add_params(arg) auth(@params) if @params.length > 0 elsif arg.is_a?(String) auth(arg) end end def params @params ||= {} end def add_params(params_to_add) params.merge!(collect_known_params params_to_add) end def get(path, req_params={}) req_params = apply_auth(req_params) RestClient.get(url(path, req_params), :accept => :json) do |response, request, result, &block| Fanforce::Response.process(response, request, complete_url(path), req_params) end end def url(path, req_params={}) req_params = apply_auth(req_params) "#{complete_url(path)}?#{to_query_string(req_params)}" end def curl_command(method, path, req_params={}) req_params = apply_auth(req_params) Fanforce::Utils.curl_command(method, complete_url(path), req_params) end def post(path, req_params={}) url = complete_url(path) req_params = apply_auth(req_params) RestClient.post(url, req_params.to_json, :content_type => :json, :accept => :json) do |response, request, result, &block| Fanforce::Api::Response.process(response, request, url, req_params) end end def put(path, req_params={}) url = complete_url(path) req_params = apply_auth(req_params) RestClient.put(url, req_params.to_json, :content_type => :json, :accept => :json) do |response, request, result, &block| Fanforce::Api::Response.process(response, request, url, req_params) end end def delete(path, req_params={}) url = complete_url(path) req_params = apply_auth(req_params) RestClient.delete(url, {:params => to_query_string(req_params), :accept => :json}) do |response, request, result, &block| Fanforce::Api::Response.process(response, request, url, req_params) end end def identify(req_params) post '/bie/identify', req_params {success: true} end def track(plugin_id, req_params) post '/bie/track', req_params.merge(plugin_id: plugin_id) {success: true} end def auth(auth_data=nil) @auth_hash ||= {} return @auth_hash if is_blank?(auth_data) auth_data = auth_data.is_a?(Hash) ? auth_data.symbolize_keys : {api_key: auth_data.to_s} @auth_hash.merge! remove_nil_values(api_key: auth_data[:api_key], fanforce_id: auth_data[:fanforce_id], fanforce_slug: auth_data[:fanforce_slug]) params.merge!(@auth_hash) valid_auth? end def valid_auth? is_present?(@auth_hash) and is_present?(@auth_hash[:api_key]) and is_present?(@auth_hash[:fanforce_id]) end def apply_auth(req_params) req_params.merge(@auth_hash || {}) end def complete_url(path) 'http://' + $API_DOMAIN + path end end