rubyzip/samples/example_recursive.rb

57 lines
1.6 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2014-03-31 19:20:27 +08:00
require 'zip'
# 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:
2016-03-22 18:24:28 +08:00
# directory_to_zip = "/tmp/input"
# output_file = "/tmp/out.zip"
# zf = ZipFileGenerator.new(directory_to_zip, output_file)
# zf.write()
class ZipFileGenerator
# Initialize with the directory to zip and the location of the output archive.
def initialize(input_dir, output_file)
@input_dir = input_dir
@output_file = output_file
end
# Zip the input directory.
def write
2017-06-29 10:57:12 +08:00
entries = Dir.entries(@input_dir) - %w[. ..]
::Zip::File.open(@output_file, create: true) do |zipfile|
2017-04-17 13:53:10 +08:00
write_entries entries, '', zipfile
2015-06-08 15:18:12 +08:00
end
end
private
2015-06-08 15:18:12 +08:00
# A helper method to make the recursion work.
2017-04-17 13:53:10 +08:00
def write_entries(entries, path, zipfile)
2015-03-21 16:10:37 +08:00
entries.each do |e|
2017-04-17 13:53:10 +08:00
zipfile_path = path == '' ? e : File.join(path, e)
disk_file_path = File.join(@input_dir, zipfile_path)
2015-06-08 15:18:12 +08:00
if File.directory? disk_file_path
2017-04-17 13:53:10 +08:00
recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
else
2017-04-17 13:53:10 +08:00
put_into_archive(disk_file_path, zipfile, zipfile_path)
end
2015-03-21 16:10:37 +08:00
end
end
2015-06-08 15:18:12 +08:00
2017-04-17 13:53:10 +08:00
def recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
zipfile.mkdir zipfile_path
2017-06-29 10:57:12 +08:00
subdir = Dir.entries(disk_file_path) - %w[. ..]
2017-04-17 13:53:10 +08:00
write_entries subdir, zipfile_path, zipfile
2015-06-08 15:18:12 +08:00
end
2017-04-17 13:53:10 +08:00
def put_into_archive(disk_file_path, zipfile, zipfile_path)
zipfile.add(zipfile_path, disk_file_path)
2015-06-08 15:18:12 +08:00
end
end