class ZipFileGenerator
This is a simple example which uses rubyzip to recursively generate a zip file from the contents of a specified directory. The directory itself is not included in the archive, rather just its contents.
Usage:
directoryToZip = "/tmp/input" output_file = "/tmp/out.zip" zf = ZipFileGenerator.new(directory_to_zip, output_file) zf.write()
Public Class Methods
new(input_dir, output_file)
click to toggle source
Initialize with the directory to zip and the location of the output archive.
# File lib/helper/zip_file_generator.rb, line 16 def initialize(input_dir, output_file) @input_dir = input_dir @output_file = output_file end
Public Instance Methods
write()
click to toggle source
Zip the input directory.
# File lib/helper/zip_file_generator.rb, line 22 def write entries = Dir.entries(@input_dir) - %w(. ..) ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |io| write_entries entries, '', io end end
Private Instance Methods
put_into_archive(disk_file_path, io, zip_file_path)
click to toggle source
ignore :reek:UtilityFunction
# File lib/helper/zip_file_generator.rb, line 54 def put_into_archive(disk_file_path, io, zip_file_path) io.add(zip_file_path, disk_file_path) end
recursively_deflate_directory(disk_file_path, io, zip_file_path)
click to toggle source
# File lib/helper/zip_file_generator.rb, line 47 def recursively_deflate_directory(disk_file_path, io, zip_file_path) io.mkdir zip_file_path subdir = Dir.entries(disk_file_path) - %w(. ..) write_entries subdir, zip_file_path, io end
write_entries(entries, path, io)
click to toggle source
A helper method to make the recursion work.
# File lib/helper/zip_file_generator.rb, line 33 def write_entries(entries, path, io) entries.each do |entry| zip_file_path = path == '' ? entry : File.join(path, entry) disk_file_path = File.join(@input_dir, zip_file_path) puts " Deflating #{disk_file_path}" if File.directory? disk_file_path recursively_deflate_directory(disk_file_path, io, zip_file_path) else put_into_archive(disk_file_path, io, zip_file_path) end end end