Edit: Modified code to remove target file if it exists beforehand.
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
if File.exist?(f_path) then
FileUtils.rm_rf f_path
end
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
Edit: Modified code to remove target directory if it exists beforehand.
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
if File.exist?(destination) then
FileUtils.rm_rf destination
end
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
Here's the original code from Mark Needham:
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exist?(f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')