Sha256: 7894c81ad5216fd9d0fb9d546aea2fa6934874b87e8cfc3572caead237969b63

Contents?: true

Size: 1.29 KB

Versions: 8

Compression:

Stored size: 1.29 KB

Contents

module Webmachine
  # {ChunkedBody} is used to wrap an {Enumerable} object (like an enumerable
  # {Response#body}) so it yields proper chunks for chunked transfer encoding.
  #
  #     case response.body
  #     when String
  #       socket.write(response.body)
  #     when Enumerable
  #       Webmachine::ChunkedBody.new(response.body).each do |chunk|
  #         socket.write(chunk)
  #       end
  #     end
  #
  # This is needed for Ruby webservers which don't do the chunking themselves.
  class ChunkedBody
    # Delimiter for chunked encoding
    CRLF = "\r\n"

    # Final chunk in any chunked-encoding response
    FINAL_CHUNK = "0#{CRLF}#{CRLF}"

    # Creates a new {ChunkedBody} from the given {Enumerable}.
    # @param [Enumerable] body the enumerable response body
    # @return [ChunkedBody] the wrapped response body
    def initialize(body)
      @body = body
    end

    # Calls the given block once for each chunk, passing that chunk as a
    # parameter.
    # Returns an {Enumerator} if no block is given.
    def each
      return self.to_enum unless block_given?

      @body.each do |chunk|
        size = chunk.bytesize
        next if size == 0
        yield([size.to_s(16), CRLF, chunk, CRLF].join)
      end
      yield(FINAL_CHUNK)
    end
  end # class ChunkedBody
end # module Webmachine

Version data entries

8 entries across 7 versions & 1 rubygems

Version Path
webmachine-1.2.2 lib/webmachine/chunked_body.rb
webmachine-1.2.0 lib/webmachine/chunked_body.rb
webmachine-1.1.0 lib/webmachine/chunked_body.rb
webmachine-1.0.0 lib/webmachine/chunked_body.rb
webmachine-0.4.2 lib/webmachine/chunked_body.rb
webmachine-0.4.1 pkg/webmachine-0.4.0/lib/webmachine/chunked_body.rb
webmachine-0.4.1 lib/webmachine/chunked_body.rb
webmachine-0.4.0 lib/webmachine/chunked_body.rb