Class: RubstApi::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/rubst_api/responses.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content = nil, status_code: 200, headers: {}, media_type: "text/plain; charset=utf-8") ⇒ Response

Returns a new instance of Response.



9
10
11
12
# File 'lib/rubst_api/responses.rb', line 9

def initialize(content = nil, status_code: 200, headers: {}, media_type: "text/plain; charset=utf-8")
  @body, @status_code, @headers, @media_type = render(content), status_code, Headers.new(headers), media_type
  @headers["content-type"] ||= media_type
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



7
8
9
# File 'lib/rubst_api/responses.rb', line 7

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



8
9
10
# File 'lib/rubst_api/responses.rb', line 8

def headers
  @headers
end

#media_typeObject (readonly)

Returns the value of attribute media_type.



8
9
10
# File 'lib/rubst_api/responses.rb', line 8

def media_type
  @media_type
end

#status_codeObject

Returns the value of attribute status_code.



7
8
9
# File 'lib/rubst_api/responses.rb', line 7

def status_code
  @status_code
end

Instance Method Details



20
# File 'lib/rubst_api/responses.rb', line 20

def delete_cookie(key, **options) = set_cookie(key, "", max_age: 0, expires: Time.at(0), **options)

#finishObject



21
22
23
24
25
# File 'lib/rubst_api/responses.rb', line 21

def finish
  payload = Array(body)
  headers["content-length"] ||= payload.sum(&:bytesize).to_s
  [status_code, headers.to_h, payload]
end

#render(content) ⇒ Object



13
# File 'lib/rubst_api/responses.rb', line 13

def render(content) = content.nil? ? "" : content.to_s


14
15
16
17
18
19
# File 'lib/rubst_api/responses.rb', line 14

def set_cookie(key, value, max_age: nil, expires: nil, path: "/", domain: nil, secure: false, httponly: false, samesite: "lax")
  parts = ["#{key}=#{value}", ("Max-Age=#{max_age}" if max_age), ("Expires=#{expires.httpdate}" if expires),
           ("Path=#{path}" if path), ("Domain=#{domain}" if domain), ("Secure" if secure),
           ("HttpOnly" if httponly), ("SameSite=#{samesite.to_s.capitalize}" if samesite)].compact
  headers["set-cookie"] = parts.join("; ")
end