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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(zos) ⇒ BufferedZipOutputStream

Returns a new instance of BufferedZipOutputStream.



13
14
15
16
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 13

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.



21
22
23
24
25
26
27
28
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 21

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

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



30
31
32
33
34
35
36
37
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 30

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

Instance Method Details

#flushObject



53
54
55
56
57
58
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 53

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.



40
41
42
43
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 40

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



46
47
48
49
50
# File 'lib/axlsx/util/buffered_zip_output_stream.rb', line 46

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