Search code examples
rubydirectorycompressionziparchive

What is the proper way to archive files using Ruby?


My wish is to make a compressed *.zip file of any directory I choose (or allow a user to choose) through Ruby, and I'm not quite sure how to do it. I do know how to create *.zip files, just not compress actual files into an archive. I did some Googling and discovered RubyZip and a couple other resources, but RubyZip is currently in a failing build state and I'm curious on how it is done so that I won't have to fully depend on an outside resource. Any help is greatly appreciated!


Solution

  • What do you mean by "failing build state"? Ultimately, rubyzip is relying on zlib, file utilities and streaming standard libraries in core Ruby, so rubyzip itself is pure Ruby and has nothing to build. If there's an error you may want to paste that. Zipping files and directories is not straightforward, so IMO this is actually a great candidate for an external library.

    I seem to have no problem, so I'm interested in what your actual error is.

    $ gem install rubyzip
    Fetching: rubyzip-1.1.0.gem (100%) yadayada
    

    And using a slightly modified version of the example on the source homepage, you can zip a directory (recursive) passed at the command line easily:

    require 'pathname'
    require 'zip'
    
    directory = Pathname.new(ARGV.first)
    zipfile_name = "#{directory}.zip"
    
    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      Dir[File.join(directory, '**', '**')].each do |file|
        path = Pathname.new(file)
        zipfile.add(path.relative_path_from(directory), file)
      end
    end
    

    IMO, the answer in this case is to use a popular library and follow the docs. Rubyzip has had some changes recently, so it's possible that some advice you can find out there is outdated, or there might some issues that require a few tweaks. But the functionality turns out to be a heck of a wheel to reinvent.