Class: Rack::Chunked

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/rack/chunked.rb

Overview

Middleware that applies chunked transfer encoding to response bodies when the response does not include a Content-Length header.

Constant Summary

Constants included from Utils

Utils::DEFAULT_SEP, Utils::HTTP_STATUS_CODES, Utils::STATUS_WITH_NO_ENTITY_BODY

Instance Method Summary collapse

Methods included from Utils

build_nested_query, build_query, bytesize, delete_cookie_header!, escape, escape_html, normalize_params, parse_nested_query, parse_query, select_best_encoding, set_cookie_header!, unescape

Constructor Details

#initialize(app) ⇒ Chunked

Returns a new instance of Chunked.



10
11
12
# File 'lib/rack/chunked.rb', line 10

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rack/chunked.rb', line 14

def call(env)
  status, headers, body = @app.call(env)
  headers = HeaderHash.new(headers)

  if env['HTTP_VERSION'] == 'HTTP/1.0' ||
     STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
     headers['Content-Length'] ||
     headers['Transfer-Encoding']
    [status, headers.to_hash, body]
  else
    dup.chunk(status, headers, body)
  end
end

#chunk(status, headers, body) ⇒ Object



28
29
30
31
32
33
# File 'lib/rack/chunked.rb', line 28

def chunk(status, headers, body)
  @body = body
  headers.delete('Content-Length')
  headers['Transfer-Encoding'] = 'chunked'
  [status, headers.to_hash, self]
end

#closeObject



45
46
47
# File 'lib/rack/chunked.rb', line 45

def close
  @body.close if @body.respond_to?(:close)
end

#each {|["0", term, "", term].join| ... } ⇒ Object

Yields:

  • (["0", term, "", term].join)


35
36
37
38
39
40
41
42
43
# File 'lib/rack/chunked.rb', line 35

def each
  term = "\r\n"
  @body.each do |chunk|
    size = bytesize(chunk)
    next if size == 0
    yield [size.to_s(16), term, chunk, term].join
  end
  yield ["0", term, "", term].join
end