Class: Xlsxtream::ZipKitWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/xlsxtream/zip_kit_writer.rb

Constant Summary collapse

BUFFER_SIZE =
64 * 1024

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(streamer, close: []) ⇒ ZipKitWriter

Returns a new instance of ZipKitWriter.



38
39
40
41
42
43
# File 'lib/xlsxtream/zip_kit_writer.rb', line 38

def initialize(streamer, close: [])
  @streamer = streamer
  @currently_writing_file_inside_zip = nil
  @buffer = String.new
  @close = close
end

Class Method Details

.with_output_to(output) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/xlsxtream/zip_kit_writer.rb', line 8

def self.with_output_to(output)
  if output.is_a?(self)
    output
  elsif output.is_a?(ZipKit::Streamer)
    # If this is a Streamer which has already been initialized, it is likely that the streamer
    # was initialized with a Streamer.open block - it will close itself. This allows xslxstream
    # to be used with zip_kit_stream and other cases where the Streamer is managed externally
    new(output, close: [])
  elsif output.is_a?(String)
    file = File.open(output, 'wb')
    streamer = ZipKit::Streamer.new(file)
    # First the Streamer needs to be closed (to write out the central directory), then the file
    new(streamer, close: [streamer, file])
  elsif output.respond_to?(:<<) || output.respond_to?(:write)
    streamer = ZipKit::Streamer.new(output)
    new(streamer, close: [streamer])
  else
    error = <<~MSG
      An `output` object must be one of:

      * A String containing a path to a file ("workbook.xslx")
      * A ZipKit::Streamer
      * An IO-like object responding to #<< or #write

      but it was a #{output.class}
    MSG
    raise ArgumentError, error
  end
end

Instance Method Details

#<<(data) ⇒ Object



45
46
47
48
49
# File 'lib/xlsxtream/zip_kit_writer.rb', line 45

def <<(data)
  @buffer << data
  flush_buffer if @buffer.size >= BUFFER_SIZE
  self
end

#add_file(path) ⇒ Object



51
52
53
54
# File 'lib/xlsxtream/zip_kit_writer.rb', line 51

def add_file(path)
  flush_file
  @currently_writing_file_inside_zip = @streamer.write_deflated_file(path)
end

#closeObject



56
57
58
59
# File 'lib/xlsxtream/zip_kit_writer.rb', line 56

def close
  flush_file
  @close.each(&:close)
end