Sha256: 50069a768a6cbd3180ae2933088bc5d0aabf9518ec1f09abedc49a992ad08134

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

require 'multi_json'
require_relative 'collection'

module TicketingHub
  module Request

    def delete(path, options={})
      request(:delete, path, options).body
    end

    def get(path, options={}, collection_class=nil)
      TicketingHub::Collection.new self, path, options, collection_class
    end

    def patch(path, options={})
      request(:patch, path, options).body
    end

    def post(path, options={})
      request(:post, path, options).body
    end

    def put(path, options={})
      request(:put, path, options).body
    end

    def request(method, path, options={})
      force_urlencoded = options.delete(:force_urlencoded) || false
      url = options.delete(:endpoint) || api_endpoint
      conn_options = { force_urlencoded: force_urlencoded, url: url }

      connection(conn_options).send(method) do |request|
        case method
          when :get, :delete, :head
            request.url(path, options)
          when :patch, :post, :put
            request.path = path
            request.body = force_urlencoded ? options : MultiJson.dump(options) unless options.empty?
        end
        request.headers['Host'] = TicketingHub.request_host if TicketingHub.request_host
      end
    rescue TicketingHub::Unauthorized => e
      if refresh_token.present? && e.response_body == ' '
        body = post '/oauth/token', { grant_type: 'refresh_token',
          refresh_token: refresh_token, client_id: client_id, client_secret: client_secret }
        self.refresh_token = body.refresh_token
        self.access_token = body.access_token
        self.expires_at = Time.now + body.expires_in.to_i
        request method, path, options
      else raise TicketingHub::Unauthorized.new(e.response) end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ticketinghub-1.1.1 lib/ticketing_hub/request.rb
ticketinghub-1.1.0 lib/ticketing_hub/request.rb