Class: Webmachine::ChunkedBody

Inherits:
Object
  • Object
show all
Defined in:
lib/webmachine/chunked_body.rb

Overview

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.

Constant Summary

CRLF =

Delimiter for chunked encoding

"\r\n"
FINAL_CHUNK =

Final chunk in any chunked-encoding response

"0#{CRLF}#{CRLF}"

Instance Method Summary collapse

Constructor Details

#initialize(body) ⇒ ChunkedBody

Creates a new Webmachine::ChunkedBody from the given Enumerable.

Parameters:

  • body (Enumerable)

    the enumerable response body



25
26
27
# File 'lib/webmachine/chunked_body.rb', line 25

def initialize(body)
  @body = body
end

Instance Method Details

#each {|FINAL_CHUNK| ... } ⇒ Object

Calls the given block once for each chunk, passing that chunk as a parameter. Returns an Enumerator if no block is given.

Yields:



32
33
34
35
36
37
38
39
40
41
# File 'lib/webmachine/chunked_body.rb', line 32

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