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 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.
# File lib/rack/response.rb, line 22 22: def initialize(body=[], status=200, header={}) 23: @status = status.to_i 24: @header = Utils::HeaderHash.new("Content-Type" => "text/html"). 25: merge(header) 26: 27: @chunked = "chunked" == @header['Transfer-Encoding'] 28: @writer = lambda { |x| @body << x } 29: @block = nil 30: @length = 0 31: 32: @body = [] 33: 34: if body.respond_to? :to_str 35: write body.to_str 36: elsif body.respond_to?(:each) 37: body.each { |part| 38: write part.to_s 39: } 40: else 41: raise TypeError, "stringable or iterable required" 42: end 43: 44: yield self if block_given? 45: end
# File lib/rack/response.rb, line 50 50: def [](key) 51: header[key] 52: end
# File lib/rack/response.rb, line 54 54: def []=(key, value) 55: header[key] = value 56: end
# File lib/rack/response.rb, line 104 104: def close 105: body.close if body.respond_to?(:close) 106: end
# File lib/rack/response.rb, line 85 85: def each(&callback) 86: @body.each(&callback) 87: @writer = callback 88: @block.call(self) if @block 89: end
# File lib/rack/response.rb, line 108 108: def empty? 109: @block == nil && @body.empty? 110: end
# File lib/rack/response.rb, line 71 71: def finish(&block) 72: @block = block 73: 74: if [204, 205, 304].include?(status.to_i) 75: header.delete "Content-Type" 76: header.delete "Content-Length" 77: [status.to_i, header, []] 78: else 79: [status.to_i, header, self] 80: end 81: end
# File lib/rack/response.rb, line 66 66: def redirect(target, status=302) 67: self.status = status 68: self["Location"] = target 69: end
Append to body and update Content-Length.
NOTE: Do not mix # and direct # access!
# File lib/rack/response.rb, line 95 95: def write(str) 96: s = str.to_s 97: @length += Rack::Utils.bytesize(s) unless @chunked 98: @writer.call s 99: 100: header["Content-Length"] = @length.to_s unless @chunked 101: str 102: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.