Skip to content

Instantly share code, notes, and snippets.

@ampedandwired
Last active October 8, 2017 11:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ampedandwired/3385002 to your computer and use it in GitHub Desktop.
Save ampedandwired/3385002 to your computer and use it in GitHub Desktop.
Zip a directory to memory in Ruby. The rubyzip library is pretty hard to use. I tried for ages to figure out how to zip a directory to a string in memory. So here's an example that zips the given directory to a Ruby StringIO object using rubyzip.
require 'zip/zip'
def zip(dir)
Zip::ZipOutputStream::write_buffer do |zos|
Dir["#{dir}/**/**"].each do |file|
path_for_file_in_zip = file.sub(/\A#{dir}\//, '')
if !File.directory?(file)
zip_entry = zos.put_next_entry(path_for_file_in_zip)
zos << IO.read(file)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment