Class: ZipTricks::BlockWrite

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

Overview

Stashes a block given by the Rack webserver when calling each() on a body, and calls that block every time it is written to using :<< (shovel). Poses as an IO for rubyzip.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ BlockWrite

The block is the block given to each() of the Rack body, or other block you want to receive the string chunks written by the zip compressor.



9
10
11
# File 'lib/zip_tricks/block_write.rb', line 9

def initialize(&block)
  @block = block
end

Instance Method Details

#<<(buf) ⇒ Object

Every time this object gets written to, call the Rack body each() block with the bytes given instead.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/zip_tricks/block_write.rb', line 22

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

  # Ensure we ALWAYS write in binary encoding.
  encoded =
    if buf.encoding != Encoding::BINARY
      # If we got a frozen string we can't force_encoding on it
      begin
        buf.force_encoding(Encoding::BINARY)
      rescue
        buf.dup.force_encoding(Encoding::BINARY)
      end
    else
      buf
    end

  @block.call(encoded)
  self
end