require 'fanforce/errors' require 'fanforce/utils' require 'rest-client' class Fanforce include Fanforce::Utils ######################################################################## 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) params.merge!(collect_known_params params) end def get(path, params={}) url = complete_url(path) params = apply_auth(params) RestClient.get(url, {:params => params, :accept => :json}) do |response, request, result, &block| handle_response(response, request, url, params) end end def get_url(path, params={}) url = complete_url(path) params = apply_auth(params) "#{url}?#{to_query_string(params)}" end def post(path, params={}) url = complete_url(path) params = apply_auth(params) RestClient.post(url, params, {:accept => :json}) do |response, request, result, &block| handle_response(response, request, url, params) end end def put(path, params={}) url = complete_url(path) params = apply_auth(params) RestClient.put(url, params, {:accept => :json}) do |response, request, result, &block| handle_response(response, request, url, params) end end def delete(path, params={}) url = complete_url(path) params = apply_auth(params) RestClient.delete(url, {:params => params, :accept => :json}) do |response, request, result, &block| handle_response(response, request, url, params) end end def identify(params) post '/bie/identify', params {success: true} end def track(behavior_id, params) post '/bie/track', params.merge(behavior_id: behavior_id) {success: true} end def handle_response(response, request, url, params) case response.code when 200, 201 begin response = decode_json(response) rescue raise UnknownError.new(response, request, url, params) end when 400 raise BadRequestError.new(response, request, url, params) when 403 raise ForbiddenError.new(response, request, url, params) when 404 raise NotFoundError.new(response, request, url, params) when 422 raise UnprocessableEntityError.new(response, request, url, params) else raise UnknownError.new(response, request, url, params) end response 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], app_id: auth_data[:app_id], module_id: auth_data[:module_id], behavior_id: auth_data[:behavior_id], widget_id: auth_data[:widget_id]) 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(params) params.merge(@auth_hash || {}) end def complete_url(path) 'http://' + $API_DOMAIN + path end end