2014-03-31 19:20:27 +08:00
|
|
|
require 'zip'
|
2011-09-21 21:49:56 +08:00
|
|
|
|
|
|
|
# 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"
|
2015-06-01 13:00:48 +08:00
|
|
|
# output_file = "/tmp/out.zip"
|
|
|
|
# zf = ZipFileGenerator.new(directory_to_zip, output_file)
|
2011-09-21 21:49:56 +08:00
|
|
|
# zf.write()
|
|
|
|
class ZipFileGenerator
|
|
|
|
# Initialize with the directory to zip and the location of the output archive.
|
2015-06-01 13:00:48 +08:00
|
|
|
def initialize(input_dir, output_file)
|
|
|
|
@input_dir = input_dir
|
|
|
|
@output_file = output_file
|
2011-09-21 21:49:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
# Zip the input directory.
|
2015-03-21 16:16:57 +08:00
|
|
|
def write
|
2015-06-08 15:18:12 +08:00
|
|
|
entries = Dir.entries(@input_dir) - %w(. ..)
|
2011-09-21 21:49:56 +08:00
|
|
|
|
2015-06-08 15:18:12 +08:00
|
|
|
::Zip::File.open(@output_file, ::Zip::File::CREATE) do |io|
|
|
|
|
write_entries entries, '', io
|
|
|
|
end
|
2011-09-21 21:49:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2015-03-21 16:19:43 +08:00
|
|
|
|
2015-06-08 15:18:12 +08:00
|
|
|
# A helper method to make the recursion work.
|
2015-03-25 00:02:54 +08:00
|
|
|
def write_entries(entries, path, io)
|
2015-03-21 16:10:37 +08:00
|
|
|
entries.each do |e|
|
2015-06-08 15:18:12 +08:00
|
|
|
zip_file_path = path == '' ? e : File.join(path, e)
|
|
|
|
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)
|
2011-09-21 21:49:56 +08:00
|
|
|
else
|
2015-06-08 15:18:12 +08:00
|
|
|
put_into_archive(disk_file_path, io, zip_file_path)
|
2011-09-21 21:49:56 +08:00
|
|
|
end
|
2015-03-21 16:10:37 +08:00
|
|
|
end
|
2011-09-21 21:49:56 +08:00
|
|
|
end
|
2015-06-08 15:18:12 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def put_into_archive(disk_file_path, io, zip_file_path)
|
|
|
|
io.get_output_stream(zip_file_path) do |f|
|
2016-01-20 18:39:16 +08:00
|
|
|
f.write(File.open(disk_file_path, 'rb').read)
|
2015-06-08 15:18:12 +08:00
|
|
|
end
|
|
|
|
end
|
2015-06-08 15:24:36 +08:00
|
|
|
end
|