Ruby: Create A Gzipped Tar Archive

13,261

Solution 1

If you're running under unix, you could write the files out to disk, then run a system call to tar/gzip them.

`tar -czf #{file_name}.tar.gz #{file_name}`

Solution 2

This Ruby Minitar project was updated in 2009 and seems like it would solve your problem

Solution 3

The following example shows how to combine the GzipWriter class from Ruby Zlib and the TarWriter class from RubyGems to create a gzipped tar archive:

require 'rubygems/package'

filenames_and_contents = {
  "filename" => "content",
}

File.open("archive.tar.gz", "wb") do |file|
  Zlib::GzipWriter.wrap(file) do |gzip|
    Gem::Package::TarWriter.new(gzip) do |tar|
      filenames_and_contents.each_pair do |filename, content|
        tar.add_file_simple(filename, 0644, content.length) do |io|
          io.write(content)
        end
      end
    end
  end
end
Share:
13,261
Rich Apodaca
Author by

Rich Apodaca

Software developer and PhD chemist. My company is Metamolecular, maker of ChemWriter™, the 2D chemical structure editor for Web applications.

Updated on July 25, 2022

Comments

  • Rich Apodaca
    Rich Apodaca almost 2 years

    What's the best way to create a gzipped tar archive with Ruby?

    I have a Rails app that needs to create a compressed archive in response to user actions. Ideally, it would be possible to write directly to a compressed file without needing to generate intermediate temp files first. The Ruby Zlib library appears to support direct gzip compression. How can I combine this with tar output?

    A number of quasi-solutions appear to have been proposed and a lot of information appears to be out of date.

    For example, the top Google search result for "ruby tar" gives this thread, which was started in 2007 with apparently no resolution.

    Another high-ranking search result is this one describing ruby tar. It dates back to 2002, and the announcement doesn't exactly inspire confidence.

    I've also seen various reports of shelling out to unix tar and the like.

    So, I know there are a lot of ways to do this, but I'm really looking for a recommendation to the most reliable and convenient one from someone who has tried a few of the alternatives.

    Any ideas?

  • Matt Connolly
    Matt Connolly almost 13 years
    I like this - very easy. Even though it doesn't check that "tar" is installed on your system, it's a reasonable assumption if they've got ruby :) Don't forget the backticks "`" around it. SO wouldn't let me add spaces in front so they're visible.
  • Tony R
    Tony R over 12 years
    Minitar doesn't seem to allow writing tars from a stream, only from files. It can output to a stream, though.