rubyzip/samples/example_recursive.rb

52 lines
1.4 KiB
Ruby
Raw Normal View History

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:
# directoryToZip = "/tmp/input"
2014-03-31 19:20:27 +08:00
# outputFile = "/tmp/out.zip"
# zf = ZipFileGenerator.new(directoryToZip, outputFile)
# zf.write()
class ZipFileGenerator
# Initialize with the directory to zip and the location of the output archive.
def initialize(inputDir, outputFile)
@inputDir = inputDir
@outputFile = outputFile
end
# Zip the input directory.
def write
2015-03-23 01:10:52 +08:00
entries = Dir.entries(@inputDir)
entries.delete('.')
entries.delete('..')
io = Zip::File.open(@outputFile, Zip::File::CREATE)
2015-03-21 16:27:44 +08:00
writeEntries(entries, '', io)
2015-03-23 01:10:52 +08:00
io.close()
end
# A helper method to make the recursion work.
private
def writeEntries(entries, path, io)
2015-03-21 16:10:37 +08:00
entries.each do |e|
2015-03-21 16:27:44 +08:00
zipFilePath = path == '' ? e : File.join(path, e)
diskFilePath = File.join(@inputDir, zipFilePath)
2015-03-21 16:27:44 +08:00
puts 'Deflating ' + diskFilePath
if File.directory?(diskFilePath)
io.mkdir(zipFilePath)
2015-03-23 01:10:52 +08:00
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
2015-03-21 16:10:37 +08:00
end
end
2014-03-31 19:20:27 +08:00
end