Topa_14 Topa_14 - 1 month ago 10
Ruby Question

Extracting ZIP files in a directory that doesn't exist

I want to extract one single content type file from a ZIP package into a directory that doesn't yet exist. My code so far:

require 'zip'

Dir.mkdir 'new_folder'
#I create the folder

def unzip_file (file_path, destination)
Zip::File.open(file_path) { |zip_file|
zip_file.glob('*.xml'){ |f| #I want to extract .XML files only
f_path = File.join(Preprocess, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
puts "Extract file to %s" % f_path
zip_file.extract(f, f_path)
}
}
end


The folder gets successfully created, but no extraction is done at any directory. I suspect that there is something wrong within the working directory. Any help?

Answer

I believe you forgot to call your unzip method to begin with...

Nevertheless, this is how I would do this:

require 'zip'

def unzip_file (file_path, destination)
  Zip::File.open(file_path) do |zip_file| 
    zip_file.each do |f| #I want to extract .XML files only
      next unless File.extname(f.name) == '.xml'
      FileUtils.mkdir_p(destination) 
      f_path = File.join(destination, File.basename(f.name)) 
      puts "Extract file to %s" % f_path
      zip_file.extract(f, f_path) 
    end
  end
end

zip_file = 'random.zip'
out_dir = 'new_folder'
unzip_file(zip_file, out_dir)