17

I need to extract a zip file that containes many folders and files using rails ziprails gem. While also keeping the files and folders organized the way they where ziped.

This was not as straight forward as i though. Please see the solution i found beneath (added for future reference)

Ole Henrik Skogstrøm
  • 6,353
  • 10
  • 57
  • 89

2 Answers2

26

This worked for me. Gave the same result as you would expect when unzipping a zipped folder with subfolders and files.

Zip::Zip.open(file_path) do |zip_file|
  zip_file.each do |f|
    f_path = File.join("destination_path", f.name)
    FileUtils.mkdir_p(File.dirname(f_path))
    zip_file.extract(f, f_path) unless File.exist?(f_path)
  end
end

The solution from this site: http://bytes.com/topic/ruby/answers/862663-unzipping-file-upload-ruby

Deepak Lamichhane
  • 19,076
  • 4
  • 30
  • 42
Ole Henrik Skogstrøm
  • 6,353
  • 10
  • 57
  • 89
10

Extract Zip archives in Ruby

You need the rubyzip gem for this. Once you've installed it, you can use this method to extract zip files:

require 'zip'

def extract_zip(file, destination)
  FileUtils.mkdir_p(destination)

  Zip::File.open(file) do |zip_file|
    zip_file.each do |f|
      fpath = File.join(destination, f.name)
      zip_file.extract(f, fpath) unless File.exist?(fpath)
    end
  end
end

You use it like this:

file_path   = "/path/to/my/file.zip"
destination = "/extract/destination/"

extract_zip(file_path, destination)
Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • This is not just the same as the accepted answer. You even posted the same answer two times: https://stackoverflow.com/a/37195592/322020 that is against SO rules. – Nakilon May 16 '19 at 23:56