Edit: Modified code to delete the target file if it exists in advance.
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 delete the target directory, if it exists in advance.
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 is the source 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')
bernie
source share