require 'fanforce/errors' require 'fanforce/utils' require 'rest-client' class Fanforce include Fanforce::Utils ######################################################################## def initialize(auth_data=nil) auth(auth_data) if is_present?(auth_data) 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(url) RestClient.delete(url, {:query => params, :accept => :json}) do |response, request, result, &block| handle_response(response, request, url, params) end 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) if is_present?(auth_data) auth_data = auth_data.is_a?(Hash) ? auth_data.symbolize_keys : {api_key: auth_data.to_s} @auth_hash ||= {} @auth_hash[:api_key] = auth_data[:api_key] if is_present?(auth_data[:api_key]) @auth_hash[:fanforce_id] = auth_data[:fanforce_id] if is_present?(auth_data[:fanforce_id]) end @auth_hash end def valid_auth? is_present?(@auth_hash) and is_present?(@auth_hash[:api_key]) end def apply_auth(params) params.merge(@auth_hash || {}) end def complete_url(path) 'http://' + $API_DOMAIN + path end end