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 = ‘http://www.example.com/download/zip/’
#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:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic) Firefox/3.5.9”, “From” => “foo@bar.com”, “Referer” => “http://www.foo.bar/”) {|zf|
#zf is an instance of class Tempfile
Zip::ZipFile.open(zf.path) do |zipfile|
#zipfile.class is Zip::ZipFile
zipfile.each{|e|
#e is an instance of Zip::ZipEntry
fpath = File.join(file_name, e.to_s)
FileUtils.mkdir_p(File.dirname(fpath))
#the block is for handling an existing file. returning true will overwrite the files.
zipfile.extract(e, fpath){ true }
}
end
}
end
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. :)