Created
October 30, 2015 06:05
-
-
Save v-kolesnikov/f6c74d8af206046b0190 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "zip/zip" | |
# Usage: | |
# directory_to_zip = "/tmp/input" | |
# output_file = "/tmp/out.zip" | |
# zf = ZipFileGenerator.new(directoryToZip, output_file).write | |
class ZipFileGenerator | |
EXCLUDED_ENTRIES = [".", "..", ".git"] | |
def initialize(input_dir, output_file) | |
@input_dir = input_dir | |
@output_file = output_file | |
end | |
def write | |
io = Zip::ZipFile.open(@output_file, Zip::ZipFile::CREATE) | |
write_entries(strip_entries(@input_dir), "", io) | |
io.close | |
end | |
private | |
def write_entries(entries, path, io) | |
entries.each do |e| | |
byebug | |
zip_file_path = path.blank? ? e : File.join(path, e) | |
disk_file_path = File.join(@input_dir, zip_file_path) | |
if File.directory?(disk_file_path) | |
io.mkdir(zip_file_path) | |
subdir = strip_entries(disk_file_path) | |
write_entries(subdir, zip_file_path, io) | |
else | |
io.get_output_stream(zip_file_path) do |f| | |
f.puts(File.open(disk_file_path, "rb").read) | |
end | |
end | |
end | |
end | |
def strip_entries(dir) | |
Dir.entries(dir).delete_if { |a| EXCLUDED_ENTRIES.include?(a) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment