File: content_length.rb

package info (click to toggle)
librack-ruby 1.1.0-4%2Bsqueeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 3,196 kB
  • ctags: 1,101
  • sloc: ruby: 8,692; makefile: 9
file content (29 lines) | stat: -rw-r--r-- 766 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require 'rack/utils'

module Rack
  # Sets the Content-Length header on responses with fixed-length bodies.
  class ContentLength
    include Rack::Utils

    def initialize(app)
      @app = app
    end

    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
  end
end