Sha256: 2ab8dc1840809dafffd5d6c0d52013f9e2b96e7b4cfbd81e86f76652840d6de5

Contents?: true

Size: 1.17 KB

Versions: 3

Compression:

Stored size: 1.17 KB

Contents

module Rexpense
  class Request
    def initialize(args)
      @args = args
    end

    def run
      request.run
      request.response
    end

    private

    attr_reader :args

    def request
      @request ||= Typhoeus::Request.new(args[:url], options)
    end

    def options
      {
        method:           args[:method],
        params:           args[:params],
        body:             body,
        headers:          headers,
        accept_encoding:  "gzip",
        params_encoding: :rack
      }.reject { |_k, v| v.nil? }
    end

    def headers
      headers = args.fetch(:headers) { {} }

      {
        "Accept"         => "application/json",
        "Content-Type"   => content_type,
        "User-Agent"     => args[:user_agent],
        "Authorization"  => "Basic #{authorization_hash}"
      }.merge(headers).delete_if { |_, v| v.nil? || v.to_s.empty? }
    end

    def body
      body = args[:body]
      body = JSON.dump(body) if body.is_a?(Hash) && !args[:multipart]
      body
    end

    def authorization_hash
      ::Base64.strict_encode64("#{args[:token]}:X")
    end

    def content_type
      args[:multipart] ? nil : "application/json"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rexpense-2.1.0 lib/rexpense/request.rb
rexpense-2.0.0 lib/rexpense/request.rb
rexpense-1.0.0 lib/rexpense/request.rb