How to overwrite existing files using Rubyzip lib

digitalsanctum picture digitalsanctum · Jun 8, 2009 · Viewed 7.9k times · Source

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

Answer

Ingmar Hamer picture Ingmar Hamer · Oct 9, 2009

Just to save others the trouble:

The extract command in answer 2 is incorrect:

The third (proc) parameter is specified wtih an ampersand, meaning ruby expects it to be in {}-Brackets after the method call like this:

zipfile.extract(entry, "#{target}/#{entry}"){ true }

or (if you need more complex logic)

zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }

If you use the example given in Post #2 you'll get a "invalid arguments (3 for 2)" error...