Class: Bitly::HTTP::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/bitly/http/response.rb

Overview

The Response class handles generic responses from the API. It is made up of a status code, body and headers. The body is expected to be JSON and it will parse the body. The status should lie within the range 100 - 599 and the headers should be a hash.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status:, body:, headers:, request: nil) ⇒ Response

Creates a new Bitly::HTTP::Response object, which can be used by other objects in the library.

Examples:

response = Bitly::HTTP::Response.new(status: "200", body: "{}", headers: {})

Parameters:

  • status (String)

    The status code of the response, which should be between 100 and 599

  • body (String)

    The body of the response, a String that is valid JSON and will be parsed

  • headers (Hash)

    The response headers

Raises:

  • (ArgumentError)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bitly/http/response.rb', line 37

def initialize(status:, body:, headers:, request: nil)
  errors = []
  @status = status
  errors << "Status must be a valid HTTP status code. Received #{status}" unless is_status?(status)
  if body.nil? || body.empty?
    @body = nil
  else
    begin
      @body = JSON.parse(body)
    rescue JSON::ParserError
      @body = {
        "message" => body
      }
    end
  end
  @headers = headers
  errors << "Headers must be a hash. Received #{headers}" unless headers.is_a?(Hash)
  @request = request
  errors << "Request must be a Bitly::HTTP::Request. Received #{request}" if request && !request.is_a?(Request)
  raise ArgumentError, errors.join("\n"), caller if errors.any?
end

Instance Attribute Details

#bodyHash (readonly)

Returns The response’s parsed body.

Returns:

  • (Hash)

    The response’s parsed body



17
18
19
# File 'lib/bitly/http/response.rb', line 17

def body
  @body
end

#headersHash (readonly)

Returns The response’s headers.

Returns:

  • (Hash)

    The response’s headers



20
21
22
# File 'lib/bitly/http/response.rb', line 20

def headers
  @headers
end

#requestBitly::HTTP::Request (readonly)

Returns The request that caused this response.

Returns:



23
24
25
# File 'lib/bitly/http/response.rb', line 23

def request
  @request
end

#statusString (readonly)

Returns The response’s status code.

Returns:

  • (String)

    The response’s status code



14
15
16
# File 'lib/bitly/http/response.rb', line 14

def status
  @status
end