Class: Apia::Response

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

Constant Summary collapse

TYPES =
[
  JSON = :json,
  PLAIN = :plain
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, endpoint) ⇒ Response

Returns a new instance of Response.



19
20
21
22
23
24
25
26
# File 'lib/apia/response.rb', line 19

def initialize(request, endpoint)
  @request = request
  @endpoint = endpoint

  @status = @endpoint.definition.http_status_code
  @fields = {}
  @headers = {}
end

Instance Attribute Details

#bodyHash

Return the body that should be returned for this response

Returns:

  • (Hash)


62
63
64
# File 'lib/apia/response.rb', line 62

def body
  @body || hash
end

#fieldsObject (readonly)

Returns the value of attribute fields.



15
16
17
# File 'lib/apia/response.rb', line 15

def fields
  @fields
end

#headersObject (readonly)

Returns the value of attribute headers.



16
17
18
# File 'lib/apia/response.rb', line 16

def headers
  @headers
end

#statusObject

Returns the value of attribute status.



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

def status
  @status
end

Instance Method Details

#add_field(name, value) ⇒ void

This method returns an undefined value.

Add a field value for this endpoint

Parameters:

  • name (Symbol)
  • value (Hash, Object, nil)


38
39
40
# File 'lib/apia/response.rb', line 38

def add_field(name, value)
  @fields[name.to_sym] = value
end

#add_header(name, value) ⇒ void

This method returns an undefined value.

Add a header to the response

Parameters:

  • name (String)
  • value (String)


47
48
49
# File 'lib/apia/response.rb', line 47

def add_header(name, value)
  @headers[name.to_s] = value&.to_s
end

#hashHash

Return the full hash of data that should be returned for this request.

Returns:

  • (Hash)


55
56
57
# File 'lib/apia/response.rb', line 55

def hash
  @hash ||= @endpoint.definition.fields.generate_hash(@fields, request: @request)
end

#plain_text_body(body) ⇒ Object



28
29
30
31
# File 'lib/apia/response.rb', line 28

def plain_text_body(body)
  @type = PLAIN
  @body = body
end

#rack_tripletArray

Return the rack triplet for this response

Returns:

  • (Array)


73
74
75
76
77
78
79
80
# File 'lib/apia/response.rb', line 73

def rack_triplet
  case type
  when JSON
    Rack.json_triplet(body, headers: headers, status: status)
  when PLAIN
    Rack.plain_triplet(body, headers: headers, status: status)
  end
end

#typeObject



66
67
68
# File 'lib/apia/response.rb', line 66

def type
  @type || JSON
end