Class: ZipTricks::BlockWrite

Inherits:
Object
  • Object
show all
Defined in:
lib/zip_tricks/block_write.rb

Overview

Acts as a converter between callers which send data to the #<< method (such as all the ZipTricks writer methods, which push onto anything), and a given block. Every time #<< gets called on the BlockWrite, the block given to the constructor will be called with the same argument. ZipTricks uses this object when integrating with Rack and in the OutputEnumerator. Normally you wouldn't need to use it manually but you always can. BlockWrite will also ensure the binary string encoding is forced onto any string that passes through it.

For example, you can create a Rack response body like so:

class MyRackResponse
  def each
    writer = ZipTricks::BlockWrite.new {|chunk| yield(chunk) }
    writer << "Hello" << "world" << "!"
  end
end
[200, {}, MyRackResponse.new]

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ BlockWrite

Creates a new BlockWrite.



23
24
25
# File 'lib/zip_tricks/block_write.rb', line 23

def initialize(&block)
  @block = block
end

Instance Method Details

#<<(buf) ⇒ Object

Sends a string through to the block stored in the BlockWrite.



40
41
42
43
44
45
46
# File 'lib/zip_tricks/block_write.rb', line 40

def <<(buf)
  # Zero-size output has a special meaning  when using chunked encoding
  return if buf.nil? || buf.bytesize.zero?

  @block.call(buf.b)
  self
end