Skip to content

Instantly share code, notes, and snippets.

@xarimanx
Created October 13, 2015 15:09
Show Gist options
  • Save xarimanx/3784586845b8c2d34b91 to your computer and use it in GitHub Desktop.
Save xarimanx/3784586845b8c2d34b91 to your computer and use it in GitHub Desktop.
create zip
require 'zip'
# Usage:
# directoryToZip = "/tmp/input"
# outputFile = "/tmp/out.zip"
# zf = ZipFileGenerator.new(directoryToZip, outputFile)
# zf.write()
class ZipFileGenerator
def initialize(inputDir, outputFile)
@inputDir = inputDir
@outputFile = outputFile
end
def write()
entries = Dir.entries(@inputDir); entries.delete("."); entries.delete("..")
io = Zip::File.open(@outputFile, Zip::File::CREATE);
writeEntries(entries, "", io)
io.close();
end
private
def writeEntries(entries, path, io)
entries.each { |e|
zipFilePath = path == "" ? e : File.join(path, e)
diskFilePath = File.join(@inputDir, zipFilePath)
puts "Deflating " + diskFilePath
if File.directory?(diskFilePath)
FileUtils.mkdir_p(zipFilePath)
subdir = Dir.entries(diskFilePath); subdir.delete("."); subdir.delete("..")
writeEntries(subdir, zipFilePath, io)
else
io.get_output_stream(zipFilePath) { |f| f.puts(File.open(diskFilePath, "rb").read())}
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment