Class: Axlsx::BufferedZipOutputStream

Inherits:
Object
  • Object
show all
Defined in:
lib/axlsx/util/buffered_zip_output_stream.rb

Overview

The BufferedZipOutputStream buffers the output in order to avoid appending many small strings directly to the the Zip::OutputStream.

The methods provided here mimic Zip::OutputStream so that this class can be used a drop-in replacement.

Constant Summary collapse

BUFFER_SIZE =

The 4_096 was chosen somewhat arbitrary, however, it was difficult to see any obvious improvement with larger buffer sizes.

4_096
SUPPRESS_ZIP64 =

The suppress_extra_fields method was introduced in rubyzip 3.2 Between rubyzip 3.0 and 3.2, it automatically writes zip64 support to the xlsx files See: https://github.com/caxlsx/caxlsx/issues/481

Zip::OutputStream.method(:open).parameters.any? { |_, key| key == :suppress_extra_fields } ? { suppress_extra_fields: :zip64 } : {}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(zos) ⇒ BufferedZipOutputStream

Returns a new instance of BufferedZipOutputStream.



17
18
19
20
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 17

def initialize(zos)
  @zos = zos
  @buffer = String.new(capacity: BUFFER_SIZE * 2)
end

Class Method Details

.open(file_name, encrypter = nil) ⇒ Object

Create a temporary directory for writing files to.

The directory and its contents are removed at the end of the block.



25
26
27
28
29
30
31
32
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 25

def self.open(file_name, encrypter = nil)
  Zip::OutputStream.open(file_name, encrypter: encrypter, **SUPPRESS_ZIP64) do |zos|
    bzos = new(zos)
    yield(bzos)
  ensure
    bzos.flush if bzos
  end
end

.write_buffer(io = ::StringIO.new, encrypter = nil) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 34

def self.write_buffer(io = ::StringIO.new, encrypter = nil)
  Zip::OutputStream.write_buffer(io, encrypter: encrypter, **SUPPRESS_ZIP64) do |zos|
    bzos = new(zos)
    yield(bzos)
  ensure
    bzos.flush if bzos
  end
end

Instance Method Details

#flushObject



57
58
59
60
61
62
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 57

def flush
  return if @buffer.empty?

  @zos << @buffer
  @buffer.clear
end

#put_next_entry(entry) ⇒ Object

Closes the current entry and opens a new for writing.



44
45
46
47
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 44

def put_next_entry(entry)
  flush
  @zos.put_next_entry(entry)
end

#write(content) ⇒ Object Also known as: <<

Write to a buffer that will be written to the current entry



50
51
52
53
54
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 50

def write(content)
  @buffer << content.to_s
  flush if @buffer.size > BUFFER_SIZE
  self
end