Monday, March 7, 2011

Short Rubyzip tutorial

Rubyzip is a handy tool for creating zip files with a Ruby script. But to me, the documentation doesn't make it immediately obvious how to use the thing. This quick tutorial should get you started.

Say you're submitting some pictures of kitchen gadgets to Strange Cooks Weekly. You need to zip up your images before sending them, and you're contractually obligated to use Ruby to do it. Here's how.

require 'rubygems'
require 'zip/zip'

puts "Zipping files!"

file_path = "Users/me/Pictures/kitchen_implements"
file_list = ['toast_mitten.png', 'gravy_jug.png', 'biscuit_juicer.png']

zipfile_name = "/Users/me/Desktop/someFile.zip"

Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile|
  file_list.each do |filename|
    # Two arguments:
    # - The name of the file as it will appear in the archive
    # - The original file, including the path to find it
    zipfile.add(filename, file_path + '/' + filename)
  end
end

Note that if the zip file already exists, this script will try to add stuff to it. If you try to add a file that's already in the archive, it will complain.