module Itrigga module AdminApiClient include Trigga::ParamFu include Itrigga::AdminApiClient::Proxies::Admin include Itrigga::AdminApiClient::Proxies::Api include Itrigga::AdminApiClient::Proxies::SearchTracker private def self.make_call(module_name, endpoint, opts = {}) require_param(opts, :api_key) host = make_absolute_url( opts[:host] || TRIGGA_ADMIN_API_CLIENT_CONFIG[module_name].base_url ) begin url = build_url(host,endpoint,opts) Itrigga.add_log_line("[API Client] - #{url}") response = JSON.parse(Itrigga::NetHelper.do_get(url)) ::Hashie::Mash.new(response.kind_of?(Array) ? default_response : response.merge(default_response) ) rescue Exception => e Itrigga.add_log_line "[API Client Error] - #{e.message}\n#{e.backtrace.join('\n')}" if RAILS_ENV == "development" ::Hashie::Mash.new(:error => e.message, :status_code => status_code_from_error(e.message)) end end def self.default_response {:status_code => 200} end def self.make_endpoint_absolute(endpoint) endpoint.to_s.match(/^\/{1}.*/) ? endpoint : "/#{endpoint}" end def self.make_absolute_url(url) url.to_s.match(/^https?:\/\//) ? url : "http://#{url}" end def self.build_url(url, endpoint, h = {}) # default format to json format = h[:format] || "json" h.delete :format params = h.map { |k, v| "#{k}=#{v}" }.join("&") "#{url}#{make_endpoint_absolute(endpoint)}.#{format}#{params.empty? ? '' : '?' + params}" end # get the status code from the error message # eg "404 Not Found" def self.status_code_from_error(error) code = error.match(/^(\d{3} )/) if code code.to_s.to_i else 0 end end end # ============================================================================================================================== # Prints a debugging info line into the log... # ============================================================================================================================== def self.add_log_line(line, add_padding = false) is_terminal = false begin @terminal_width ||= `stty size`.split.map { |x| x.to_i }.reverse[0] is_terminal = true rescue Exception => e # not running in terminal`` end if add_padding and is_terminal and !@terminal_width.nil? puts "#{line.ljust(@terminal_width - line.length, "=")}\n" else if defined?(Rails.logger) Rails.logger.info line else puts line end end end end