Rack::Response provides a convenient interface to create a Rack response.
It allows setting of headers and cookies, and provides useful defaults (a OK response containing HTML).
You can use #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 syncronous with the Rack
response.
Your application’s call
should end returning #finish.
# File lib/rack/response.rb, line 22 def initialize(body=[], status=200, header={}, &block) @status = status.to_i @header = Utils::HeaderHash.new({"Content-Type" => "text/html"}. merge(header)) @writer = lambda { |x| @body << x } @block = nil @length = 0 @body = [] if body.respond_to? :to_str write body.to_str elsif body.respond_to?(:each) body.each { |part| write part.to_s } else raise TypeError, "stringable or iterable required" end yield self if block_given? end
# File lib/rack/response.rb, line 49 def [](key) header[key] end
# File lib/rack/response.rb, line 53 def []=(key, value) header[key] = value end
# File lib/rack/response.rb, line 101 def close body.close if body.respond_to?(:close) end
# File lib/rack/response.rb, line 82 def each(&callback) @body.each(&callback) @writer = callback @block.call(self) if @block end
# File lib/rack/response.rb, line 105 def empty? @block == nil && @body.empty? end
# File lib/rack/response.rb, line 70 def finish(&block) @block = block if [204, 304].include?(status.to_i) header.delete "Content-Type" [status.to_i, header, []] else [status.to_i, header, self] end end
# File lib/rack/response.rb, line 65 def redirect(target, status=302) self.status = status self["Location"] = target end