Download a zip file and extract using RubyZip

Yesterday I found myself needing to download a zipfile and extract the contents. While this is easy in a shell script, in Ruby its quite aggravating. After some Googling I ended up using RubyZip, but I hope there are better libraries out there. This one doesn’t seem very intuitive. I’ll let the code do the talking here. I’ve added comments so it make sense.
If there is a smoother/less painful|bad way of doing this I’m all ears.

require ‘rubygems’
require ‘open-uri’
require ‘zip/zip’
require ‘fileutils’

def download_zip file_name
url = ‘’
#the website will drop the connection without the user-agent and other stuff.
open( url + file_name, “User-Agent” => “Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv: Gecko/20100402 Ubuntu/9.10 (karmic) Firefox/3.5.9”, “From” => “”, “Referer” => “”) {|zf|
#zf is an instance of class Tempfile do |zipfile|
#zipfile.class is Zip::ZipFile
#e is an instance of Zip::ZipEntry
fpath = File.join(file_name, e.to_s)
#the block is for handling an existing file. returning true will overwrite the files.
zipfile.extract(e, fpath){ true }

In my searches I noticed a few mentions about how poor the documentation for this library is. Its a little surprising how difficult it is to come up with one clear example of this. Hopefully this can serve as a starting point for someone and save them some aggravation. Forgive the formatting. :)


One thought on “Download a zip file and extract using RubyZip”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s