Class: Forem::ForemResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/forem/forem_response.rb

Overview

Wraps a raw HTTP response from the Forem API.

ForemResponse is an internal value object created by APIRequestor after every successful round-trip to the server. It normalises the Net::HTTP response into a simple struct and provides lazy JSON parsing via #parsed_body.

Examples:

Inspecting a raw response (inside a custom requestor)

resp = requestor.request(:get, "/api/articles/1")
resp.http_status   #=> 200
resp.parsed_body   #=> { "id" => 1, "title" => "Hello" }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_status:, http_body:, http_headers:) ⇒ ForemResponse

Create a new ForemResponse.

Parameters:

  • http_status (Integer)

    the HTTP status code.

  • http_body (String)

    the raw response body.

  • http_headers (Hash)

    the response headers.



32
33
34
35
36
# File 'lib/forem/forem_response.rb', line 32

def initialize(http_status:, http_body:, http_headers:)
  @http_status = http_status
  @http_body = http_body
  @http_headers = http_headers
end

Instance Attribute Details

#http_bodyString (readonly)

Returns the raw, unparsed HTTP response body as a string.

Returns:

  • (String)

    the raw, unparsed HTTP response body as a string.



20
21
22
# File 'lib/forem/forem_response.rb', line 20

def http_body
  @http_body
end

#http_headersHash (readonly)

Returns a hash of downcased HTTP response header names to their string values (e.g. { "content-type" => "application/json" }).

Returns:

  • (Hash)

    a hash of downcased HTTP response header names to their string values (e.g. { "content-type" => "application/json" }).



24
25
26
# File 'lib/forem/forem_response.rb', line 24

def http_headers
  @http_headers
end

#http_statusInteger (readonly)

Returns the HTTP status code of the response (e.g. 200, 404).

Returns:

  • (Integer)

    the HTTP status code of the response (e.g. 200, 404).



17
18
19
# File 'lib/forem/forem_response.rb', line 17

def http_status
  @http_status
end

Instance Method Details

#parsed_bodyHash, ...

Parse the response body as JSON, caching the result after the first call.

Returns nil when the body is absent or blank (e.g. HTTP 204 No Content).

Returns:

  • (Hash, Array, nil)

    the decoded JSON value, or nil if the body is empty.

Raises:

  • (JSON::ParserError)

    if the body is non-empty but not valid JSON.



45
46
47
48
# File 'lib/forem/forem_response.rb', line 45

def parsed_body
  return nil if http_body.nil? || http_body.empty?
  @parsed_body ||= JSON.parse(http_body)
end