Class: IOStreams::Zip::Writer
- Inherits:
-
Object
- Object
- IOStreams::Zip::Writer
- Defined in:
- lib/io_streams/zip/writer.rb
Class Method Summary collapse
-
.open(file_name_or_io, zip_file_name: nil, buffer_size: 65536, &block) ⇒ Object
Write a single file in Zip format to the supplied output file name.
Class Method Details
.open(file_name_or_io, zip_file_name: nil, buffer_size: 65536, &block) ⇒ Object
Write a single file in Zip format to the supplied output file name
Parameters
file_name_or_io [String]
Full path and filename for the output zip file
zip_file_name: [String]
Name of the file within the Zip Stream
The stream supplied to the block only responds to #write
Example:
IOStreams::ZipWriter.open('myfile.zip', zip_file_name: 'myfile.txt') do |io_stream|
io_stream.write("hello world\n")
io_stream.write("and more\n")
end
Notes:
-
Since Zip cannot write to streams, if a stream is supplied, a temp file is automatically created under the covers
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/io_streams/zip/writer.rb', line 24 def self.open(file_name_or_io, zip_file_name: nil, buffer_size: 65536, &block) # Default the name of the file within the zip to the supplied file_name without the zip extension zip_file_name = file_name_or_io.to_s[0..-5] if zip_file_name.nil? && !IOStreams.writer_stream?(file_name_or_io) && (file_name_or_io =~ /\.(zip)\z/) zip_file_name ||= 'file' if !defined?(JRuby) && !defined?(::Zip) # MRI needs Ruby Zip, since it only has native support for GZip begin require 'zip' rescue LoadError => exc raise(LoadError, "Install gem 'rubyzip' to read and write Zip files: #{exc.message}") end end # File name supplied return write_file(file_name_or_io, zip_file_name, &block) unless IOStreams.writer_stream?(file_name_or_io) # Stream supplied begin # Since ZIP cannot be streamed, download to a local file before streaming temp_file = Tempfile.new('rocket_job') temp_file.binmode write_file(temp_file.to_path, zip_file_name, &block) # Stream temp file into output stream IOStreams.copy(temp_file, file_name_or_io, buffer_size: buffer_size) ensure temp_file.delete if temp_file end end |