module Response
Response helpers for Utopia applications.
The canonical transport response remains Protocol::HTTP::Response. This
module provides convenience constructors and normalization at the application
boundary.
Definitions
def self.[](status, headers = nil, body = nil, **options)
Build a protocol HTTP response.
Signature
-
parameter
statusInteger The HTTP status code.
-
parameter
headersHash | Protocol::HTTP::Headers | Nil The response headers.
-
parameter
bodyObject The response body.
-
parameter
optionsHash Additional options passed to
Protocol::HTTP::Response[].-
returns
Protocol::HTTP::Response The response object.
Implementation
def self.[](status, headers = nil, body = nil, **options)
Protocol::HTTP::Response[status, headers, body, **options]
end
def self.wrap(response)
Normalize a response-like value to a protocol response.
Signature
-
parameter
responseObject The response-like value.
-
returns
Protocol::HTTP::Response The normalized response.
-
raises
TypeError If the response cannot be normalized.
Implementation
def self.wrap(response)
return response if response.is_a?(Protocol::HTTP::Response)
if response.respond_to?(:to_response)
response = response.to_response
return response if response.is_a?(Protocol::HTTP::Response)
end
raise TypeError, "Expected a Protocol::HTTP::Response, but got #{response.class}!"
end
def self.redirect(location, status = 302, headers = {})
Build a redirect response.
Signature
-
parameter
locationString The redirect location.
-
parameter
statusInteger The redirect status code.
-
parameter
headersHash Additional response headers.
-
returns
Protocol::HTTP::Response The redirect response.
Implementation
def self.redirect(location, status = 302, headers = {})
self[status, headers.merge(LOCATION => location), []]
end
def self.text(content, status = 200, headers = {})
Build a plain text response.
Signature
-
parameter
contentString The response content.
-
parameter
statusInteger The response status.
-
parameter
headersHash Additional response headers.
-
returns
Protocol::HTTP::Response The text response.
Implementation
def self.text(content, status = 200, headers = {})
self[status, {CONTENT_TYPE => "text/plain; charset=utf-8"}.merge(headers), [content]]
end
def self.html(content, status = 200, headers = {})
Build an HTML response.
Signature
-
parameter
contentString The response content.
-
parameter
statusInteger The response status.
-
parameter
headersHash Additional response headers.
-
returns
Protocol::HTTP::Response The HTML response.
Implementation
def self.html(content, status = 200, headers = {})
self[status, {CONTENT_TYPE => "text/html; charset=utf-8"}.merge(headers), [content]]
end