Sha256: 8841de67ff073db66da1418d1d54353d8bcde6447234c446a28383d60572f474

Contents?: true

Size: 1.39 KB

Versions: 9

Compression:

Stored size: 1.39 KB

Contents

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"
#   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(input_dir, output_file)
    @input_dir = input_dir
    @output_file = output_file
  end

  # Zip the input directory.
  def write
    entries = Dir.entries(@input_dir)
    entries.delete('.')
    entries.delete('..')
    io = Zip::File.open(@output_file, Zip::File::CREATE)

    write_entries(entries, '', io)
    io.close
  end

  # A helper method to make the recursion work.
  private

  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)
      if File.directory?(disk_file_path)
        io.mkdir(zip_file_path)
        subdir = Dir.entries(disk_file_path)
        subdir.delete('.')
        subdir.delete('..')
        write_entries(subdir, zip_file_path, io)
      else
        io.get_output_stream(zip_file_path) { |f| f.puts(File.open(disk_file_path, 'rb').read) }
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 2 rubygems

Version Path
sunomono-1.0.6 lib/helpers/zip_helpers.rb
sunomono-1.0.5 lib/helpers/zip_helpers.rb
sunomono-1.0.4 lib/helpers/zip_helpers.rb
sunomono-1.0.3 lib/helpers/zip_helpers.rb
sunomono-1.0.0 lib/helpers/zip_helpers.rb
sunomono-0.3.1 lib/helpers/zip_helpers.rb
sunomono-0.3.0 lib/helpers/zip_helpers.rb
sunomono-0.2.0.pre lib/helpers/zip_helpers.rb
cs-bdd-0.1.9 lib/cs/bdd/zip.rb