module Roda::RodaPlugins::Base::ResponseMethods
Instance methods for RodaResponse
Constants
- CONTENT_LENGTH
- CONTENT_TYPE
- DEFAULT_CONTENT_TYPE
- LOCATION
Attributes
The hash of response headers for the current response.
The status code to use for the response. If none is given, will use 200 code for non-empty responses and a 404 code for empty responses.
Public Class Methods
Set the default headers when creating a response.
# File lib/roda.rb, line 890 def initialize @status = nil @headers = default_headers @body = [] @length = 0 end
Public Instance Methods
Return the response header with the given key. Example:
response['Content-Type'] # => 'text/html'
# File lib/roda.rb, line 900 def [](key) @headers[key] end
Set the response header with the given key to the given value.
response['Content-Type'] = 'application/json'
# File lib/roda.rb, line 907 def []=(key, value) @headers[key] = value end
The default headers to use for responses.
# File lib/roda.rb, line 917 def default_headers {CONTENT_TYPE => DEFAULT_CONTENT_TYPE} end
Whether the response body has been written to yet. Note that writing an empty string to the response body marks the response as not empty. Example:
response.empty? # => true response.write('a') response.empty? # => false
# File lib/roda.rb, line 939 def empty? @body.empty? end
Return the rack response array of status, headers, and body for the current response. Example:
response.finish # => [200, {'Content-Type'=>'text/html'}, []]
# File lib/roda.rb, line 947 def finish b = @body s = (@status ||= b.empty? ? 404 : 200) [s, @headers, b] end
Show response class, status code, response headers, and response body
# File lib/roda.rb, line 912 def inspect "#<#{self.class.inspect} #{@status.inspect} #{@headers.inspect} #{@body.inspect}>" end
Set the Location header to the given path, and the status to the given status. Example:
response.redirect('foo', 301) response.redirect('bar')
# File lib/roda.rb, line 958 def redirect(path, status = 302) @headers[LOCATION] = path @status = status end
Write to the response body. Updates Content-Length header with the size of the string written. Returns nil. Example:
response.write('foo') response['Content-Length'] # =>'3'
# File lib/roda.rb, line 976 def write(str) s = str.to_s @length += s.bytesize @headers[CONTENT_LENGTH] = @length.to_s @body << s nil end