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 collapse

FINAL_CHUNK =

Final chunk in any chunked-encoding response

"0#{CRLF}#{CRLF}".freeze

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



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

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:



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

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