Search code examples
rubyrubyzip

How to unzip a file with ruby


Okay I've found the following code for unzippping a file with Ruby.

def unzip_file (file, destination)
    Zip::ZipFile.open(file_path) { |zip_file|
        zip_file.each { |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

Above this I'm using the following to ensure the needed gems are installed.

begin
    require 'rubygems'
rescue LoadError
    'gem install rubygems'
end
begin
    require 'zip/zip'
rescue LoadError
    'gem install rubyzip'
end

So when I call unzip_file I get the following error:

in `unzip_file': uninitialized constant Zip (NameError)

What am I doing wrong? Thanks!


Solution

  • The problem with installing the gem that way is that you're shelling out to another process with:

    `gem install rubyzip`
    

    and after that finishes installing the gem, your current irb session still won't see it. You'd have to reload irb with exec "irb" and then calling require 'zip' again.

    Note: those are backticks not single quotes.

    Try this:

    begin
        require 'zip'
    rescue LoadError
        `gem install rubyzip`
        exec "irb"
        retry
    end
    

    For me require 'zip' works. I have rubyzip-1.1.2

    Now you should be able to use Zip

    Also, the gem command is rubygems. So you can't install rubygems with itself. It should already be installed, but if not try this: http://rubygems.org/pages/download