I’m attempting to unzip a file with several files that may or may not already exist in the target directory. It seems the default behavior is to throw an exception if the file already exists.
How do I unzip to a directory and simply overwrite existing files?
Here’s my code:
begin
Zip::ZipFile.open(source) do |zipfile|
dir = zipfile.dir
dir.entries('.').each do |entry|
zipfile.extract(entry, "#{target}/#{entry}")
end
end
rescue Exception => e
log_error("Error unzipping file: #{local_zip} #{e.to_s}")
end
It appears that extract() takes an optional block (onExistsProc) that allows you to determine what to do with the file if it already exists – return true to overwrite, false to raise an exception.
If you wanted to simply overwrite all existing files, you could do:
If you want to do some more complex logic to handle specific entries differently, you can do:
EDIT: fixed answer – as pointed out by Ingmar Hamer, my original answer passed the block as a parameter when it’s expected using the above syntax.