class Rack::Response
Rack::Response
provides a convenient interface to create a Rack
response.
It allows setting of headers and cookies, and provides useful defaults (an OK response with empty headers and body).
You can use Response#write
to iteratively generate your response, but note that this is buffered by Rack::Response
until you call finish
. finish
however can take a block inside which calls to write
are synchronous with the Rack
response.
Your application’s call
should end returning Response#finish
.
Constants
- CHUNKED
- STATUS_WITH_NO_ENTITY_BODY
Attributes
Public Class Methods
Source
# File lib/rack/response.rb, line 19 def self.[](status, headers, body) self.new(body, status, headers) end
Source
# File lib/rack/response.rb, line 42 def initialize(body = nil, status = 200, headers = {}) @status = status.to_i @headers = Utils::HeaderHash[headers] @writer = self.method(:append) @block = nil # Keep track of whether we have expanded the user supplied body. if body.nil? @body = [] @buffered = true @length = 0 elsif body.respond_to?(:to_str) @body = [body] @buffered = true @length = body.to_str.bytesize else @body = body @buffered = false @length = 0 end yield self if block_given? end
Initialize the response object with the specified body, status and headers.
@param body [nil, each
, to_str] the response body. @param status [Integer] the integer status as defined by the HTTP protocol RFCs. @param headers [#each] a list of key-value header pairs which conform to the HTTP protocol RFCs.
Providing a body which responds to to_str is legacy behaviour.
Public Instance Methods
Source
# File lib/rack/response.rb, line 73 def chunked? CHUNKED == get_header(TRANSFER_ENCODING) end
Source
# File lib/rack/response.rb, line 118 def close @body.close if @body.respond_to?(:close) end
Source
# File lib/rack/response.rb, line 129 def delete_header(key); headers.delete key; end
Source
# File lib/rack/response.rb, line 98 def each(&callback) @body.each(&callback) @buffered = true if @block @writer = callback @block.call(self) end end
Source
# File lib/rack/response.rb, line 80 def finish(&block) if STATUS_WITH_NO_ENTITY_BODY[status.to_i] delete_header CONTENT_TYPE delete_header CONTENT_LENGTH close return [@status, @headers, []] else if block_given? @block = block return [@status, @headers, self] else return [@status, @headers, @body] end end end
Generate a response array consistent with the requirements of the SPEC. @return [Array] a 3-tuple suitable of ‘[status, headers, body]` which is suitable to be returned from the middleware `#call(env)` method.
Source
# File lib/rack/response.rb, line 127 def get_header(key); headers[key]; end
Source
# File lib/rack/response.rb, line 126 def has_header?(key); headers.key? key; end
Source
# File lib/rack/response.rb, line 68 def redirect(target, status = 302) self.status = status self.location = target end
Source
# File lib/rack/response.rb, line 128 def set_header(key, v); headers[key] = v; end