Sha256: ec153ee7214e7eeab5805ce8b7d49de7e9e729638b4de7c3437074a1ab06253c

Contents?: true

Size: 1.3 KB

Versions: 1

Compression:

Stored size: 1.3 KB

Contents

require 'httparty'
require 'json'

module Outreach

  class Request

    include HTTParty
    include Errors

    def initialize(access_token=nil)
      @access_token = access_token
    end

    def get(url, query={})
      response = HTTParty.get(url, query: query, headers: auth_header)
      parse_response(response)
    end

    def post(url, params)
      response_format = params.delete(:response_format) || :json
      response = HTTParty.post(url, body: params.to_json, headers: auth_header)
      parse_response(response, response_format)
    end

    def delete(url)
      response = HTTParty.delete(url, headers: auth_header)
      parse_response(response)
    end

    private

    def parse_response(response, response_format=:json)
      check_for_error(response.response.code)
      display_debug(response.body)
      if response_format == :json
        JSON.parse(response.body.to_s)
      else
        response.body.to_s
      end
    end

    def display_debug(response)
      if Outreach.debug
        puts "-" * 20 + " DEBUG " + "-" * 20
        puts response
        puts "-" * 18 + " END DEBUG " + "-" * 18
      end
    end

    def auth_header
      headers = { 'Content-Type' => 'application/json' }
      headers["Authorization"] = "Bearer #{@access_token}" if @access_token
      headers
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
outreach-0.0.1 lib/outreach/request.rb