samples/example_recursive.rb in rubyzip-1.1.7 vs samples/example_recursive.rb in rubyzip-1.2.0

- old
+ new

@@ -5,44 +5,53 @@ # a specified directory. The directory itself is not # included in the archive, rather just its contents. # # Usage: # directoryToZip = "/tmp/input" -# outputFile = "/tmp/out.zip" -# zf = ZipFileGenerator.new(directoryToZip, outputFile) +# 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(inputDir, outputFile) - @inputDir = inputDir - @outputFile = outputFile + def initialize(input_dir, output_file) + @input_dir = input_dir + @output_file = output_file end # Zip the input directory. - def write() - entries = Dir.entries(@inputDir); entries.delete("."); entries.delete("..") - io = Zip::File.open(@outputFile, Zip::File::CREATE); + def write + entries = Dir.entries(@input_dir) - %w(. ..) - writeEntries(entries, "", io) - io.close(); + ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |io| + write_entries entries, '', io + end end - # A helper method to make the recursion work. 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) - io.mkdir(zipFilePath) - subdir =Dir.entries(diskFilePath); subdir.delete("."); subdir.delete("..") - writeEntries(subdir, zipFilePath, io) + # A helper method to make the recursion work. + def write_entries(entries, path, io) + entries.each do |e| + 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) else - io.get_output_stream(zipFilePath) { |f| f.puts(File.open(diskFilePath, "rb").read())} + put_into_archive(disk_file_path, io, zip_file_path) end - } + end end + 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| + f.write(File.open(disk_file_path, 'rb').read) + end + end end