rubyrubyzip

Read zip example in readme.md - undefined local variable or method `dest_file' for main:Object (NameError)


Implementing the example code in ready.md, I get the error above. Searching through the source I can't find a method dest_file. The code I've implemented -

require 'rubygems'
require 'zip'

Zip::File.open('test.zip') do |zip_file|
  # Handle entries one by one
  zip_file.each do |entry|
    # Extract to file/directory/symlink
    puts "Extracting #{entry.name}"
    entry.extract(dest_file)

    # Read into memory
    content = entry.get_input_stream.read
  end
end

Have I understood this incorrectly? My assumption is that dest_file give the file the right metadata so it can be saved, but replacing with obvious entry.name throws an error.


Solution

  • You have not defined dest_file value. You need to specify the file name. May be you can use:

     entry.extract(entry.name)
    

    to extract the file with same name as source file name and in the current directory.


    If you want to extract to a specific dir, then, you could do something like below:

    require "zip"
    
    output_dir = "/tmp/"
    
    Zip::File.open('a.zip') do |zip_file|
      # Handle entries one by one
      zip_file.each do |entry|
        # Extract to file/directory/symlink
        puts "Extracting #{entry.name}"
        entry.extract("#{File.expand_path(output_dir)}/#{entry.name}")
      end
    end