Class: ZipKit::WriteAndTell

Inherits:
Object
  • Object
show all
Includes:
WriteShovel
Defined in:
lib/zip_kit/write_and_tell.rb

Overview

A tiny wrapper over any object that supports :<<. Adds :tell and :advance_position_by. This is needed for write destinations which do not respond to #pos or #tell. A lot of ZIP archive format parts include "offsets in archive" - a byte offset from the start of file. Keeping track of this value is what this object will do. It also allows "advancing" this value if data gets written using a bypass (such as IO#sendfile)

Instance Method Summary collapse

Methods included from WriteShovel

#write

Constructor Details

#initialize(io) ⇒ WriteAndTell

Returns a new instance of WriteAndTell.



12
13
14
15
16
17
18
19
# File 'lib/zip_kit/write_and_tell.rb', line 12

def initialize(io)
  @io = io
  @pos = 0
  # Some objects (such as ActionController::Live `stream` object) cannot be "pushed" into
  # using the :<< operator, but only support `write`. For ease we add a small shim in that case instead of having
  # the user abstract it themselves.
  @use_write = !io.respond_to?(:<<)
end

Instance Method Details

#<<(bytes) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/zip_kit/write_and_tell.rb', line 21

def <<(bytes)
  return self if bytes.nil?
  if @use_write
    @io.write(bytes.b)
  else
    @io << bytes.b
  end

  @pos += bytes.bytesize
  self
end

#advance_position_by(num_bytes) ⇒ Object



33
34
35
# File 'lib/zip_kit/write_and_tell.rb', line 33

def advance_position_by(num_bytes)
  @pos += num_bytes
end

#tellObject



37
38
39
# File 'lib/zip_kit/write_and_tell.rb', line 37

def tell
  @pos
end