Rich Apodaca
Rich Apodaca

Reputation: 29004

Ruby: Create A Gzipped Tar Archive

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?

Upvotes: 20

Views: 14507

Answers (3)

bacongravy
bacongravy

Reputation: 923

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

Upvotes: 8

Sam Saffron
Sam Saffron

Reputation: 131112

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

Upvotes: 6

Scott
Scott

Reputation: 7264

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}`

Upvotes: 12

Related Questions