ZIP archives
suggest changeWhile Ruby's standard library includes zlib for raw Deflate and .gz streams, multi-file .zip containers are commonly handled using the community-standard rubyzip gem. It provides straightforward, flexible APIs to read, create, modify, and stream ZIP archives on disk or directly in memory.
1. Installation and Configuration
Install rubyzip:
gem install rubyzip
Or add it to your Gemfile:
gem 'rubyzip', '~> 3.0'
Require and configure default behavior:
require 'zip'
# Optional configurations
Zip.warn_invalid_date = false
Zip.continue_on_exists_proc = true
Zip.unicode_names = true
2. Reading and Inspecting ZIP Archives
Use Zip::File.open with a block to ensure file handles are automatically closed:
require 'zip'
Zip::File.open('archive.zip') do |zip_file|
# Iterate over all entries (files and directories)
zip_file.each do |entry|
puts "Name: #{entry.name}"
puts "Size: #{entry.size} bytes (compressed: #{entry.compressed_size} bytes)"
puts "Directory? #{entry.directory?}"
end
# Read file content directly into memory without extracting to disk
entry = zip_file.find_entry('data/report.csv')
if entry
csv_content = entry.get_input_stream.read
puts csv_content
end
end
3. Extracting Files Safely
When extracting files from untrusted archives, guard against Zip Slip directory traversal vulnerabilities by verifying paths stay within the target destination directory:
require 'zip'
require 'fileutils'
require 'pathname'
def safe_extract(zip_path, destination_dir)
dest = Pathname.new(File.expand_path(destination_dir))
FileUtils.mkdir_p(dest)
Zip::File.open(zip_path) do |zip_file|
zip_file.each do |entry|
# Resolve target path and verify it stays inside destination
target_path = dest.join(entry.name).expand_path
unless target_path.to_s.start_with?(dest.to_s + File::SEPARATOR) || target_path == dest
raise "Unsafe zip entry path: #{entry.name}"
end
if entry.directory?
FileUtils.mkdir_p(target_path)
else
FileUtils.mkdir_p(target_path.dirname)
entry.extract(entry.name, destination_directory: dest.to_s) { true } # Overwrite if exists
end
end
end
end
safe_extract('archive.zip', './extracted_files')
4. Creating a ZIP Archive
Adding Files and Streams
Use Zip::File.open with create: true to create a new archive or add entries:
require 'zip'
Zip::File.open('output.zip', create: true) do |zip_file|
# 1. Add an existing file from the filesystem
zip_file.add('document.pdf', '/path/to/local/document.pdf')
# 2. Add content directly from a Ruby string
zip_file.get_output_stream('notes.txt') do |stream|
stream.puts "Generated on #{Time.now.utc}"
stream.puts "Server: production-node-1"
end
# 3. Create an empty directory entry
zip_file.mkdir('logs')
end
5. Zipping an Entire Directory Recursively
To zip an entire folder tree while preserving relative directory hierarchy:
require 'zip'
require 'find'
require 'pathname'
def zip_directory(directory_path, zip_output_path)
dir = Pathname.new(File.expand_path(directory_path))
Zip::File.open(zip_output_path, create: true) do |zip_file|
Find.find(dir.to_s) do |path|
next if path == dir.to_s # Skip root folder itself
entry_path = Pathname.new(path).relative_path_from(dir).to_s
if File.directory?(path)
zip_file.mkdir(entry_path)
else
zip_file.add(entry_path, path)
end
end
end
end
zip_directory('./my_project', 'project_backup.zip')
6. In-Memory ZIP Generation (e.g. for Web Downloads)
When serving a dynamic ZIP archive from a web framework (like Rails or Sinatra), generating the ZIP in a memory buffer avoids temporary disk files:
require 'zip'
def generate_zip_buffer(files_hash)
Zip::OutputStream.write_buffer do |out|
files_hash.each do |filename, content|
out.put_next_entry(filename)
out.write(content)
end
end.string
end
# Example usage in a controller or script:
zip_data = generate_zip_buffer({
'report.json' => '{"status": "ok", "items": 42}',
'readme.txt' => 'Exported on demand.'
})
# In Rails:
# send_data zip_data, filename: 'export.zip', type: 'application/zip'
File.binwrite('in_memory_export.zip', zip_data)
7. Working with Standard Library Zlib::GzipWriter
For single compressed files (.gz), Ruby's standard library zlib does not require any external gems:
require 'zlib'
# Compress data to .gz
Zlib::GzipWriter.open('archive.txt.gz') do |gz|
gz.write("Hello, compressed world!\n")
end
# Decompress data from .gz
Zlib::GzipReader.open('archive.txt.gz') do |gz|
puts gz.read
end