Class: Rack::ContentLength

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

Overview

Sets the Content-Length header on responses with fixed-length bodies.

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) ⇒ ContentLength

Returns a new instance of ContentLength.



8
9
10
# File 'lib/rack/content_length.rb', line 8

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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

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

  if !STATUS_WITH_NO_ENTITY_BODY.include?(status) &&
     !headers['Content-Length'] &&
     !headers['Transfer-Encoding'] &&
     (body.respond_to?(:to_ary) || body.respond_to?(:to_str))

    body = [body] if body.respond_to?(:to_str) # rack 0.4 compat
    length = body.to_ary.inject(0) { |len, part| len + bytesize(part) }
    headers['Content-Length'] = length.to_s
  end

  [status, headers, body]
end