require 'httpclient' require 'json' require_relative 'response' module MxHero module API module Communication # Make a HTTP call # @param method [Symbol] indicate the HTTP verb (:get, :post, :put, etc) # @param url [String] # @param body [String] (default: nil) # @param [Hash] more_options # @option more_options [Boolean] :throw_exception (default: true) throw exception if the response status are between 500 and 600 # @return [HTTP::Message](http://www.rubydoc.info/gems/httpclient/HTTP/Message) def call(method, url, body = nil, more_options = {}) unless @client @client ||= HTTPClient.new end @client.set_auth(url, @username, @password) response = @client.request(method, url, nil, body, headers) raise "Unauthorized" if response.status == 401 unless more_options[:throw_exception] == false raise "An error ocurred when try to communicate with the API\nError: #{response.inspect}" if (500..600).include?(response.status) end response end # Default headers def headers @headers ||= { 'Accept' => 'application/json', 'Content-Type' => 'application/json' } end # @return [Hash] def json_parse(json) JSON.parse(json, symbolize_names: true) end end end end