Alex Rivera | Logout

How to overwrite existing files using Rubyzip lib

Asked 2009-06-08T17:44:17.737
11

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
Edit
Report

1 Answer

18

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...

answered 2009-10-09T10:29:50.047

Your Answer