How to unzip a zip file containing folders and files in rails, while keeping the directory structure

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


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)