ruby
39 lines · 8 steps
Compress-and-encode payloads in Ruby
A module that gzips data into a Base64 string, reverses the trip safely, and reports how much space it saved.
Explained by
highlit
1require "zlib"
2require "stringio"
3require "base64"
4
5module PayloadCodec
6 module_function
7
8 def pack(data)
9 io = StringIO.new
10 io.set_encoding(Encoding::BINARY)
11 gz = Zlib::GzipWriter.new(io, Zlib::BEST_COMPRESSION)
12 begin
13 gz.write(data.to_s)
14 ensure
15 gz.close
16 end
17 Base64.strict_encode64(io.string)
18 end
19
20 def unpack(encoded)
21 raw = Base64.strict_decode64(encoded)
22 gz = Zlib::GzipReader.new(StringIO.new(raw))
23 begin
24 gz.read
25 ensure
26 gz.close
27 end
28 rescue Zlib::GzipFile::Error, ArgumentError => e
29 raise ArgumentError, "corrupt payload: #{e.message}"
30 end
31
32 def ratio(data)
33 original = data.to_s.bytesize
34 return 0.0 if original.zero?
35
36 compressed = Base64.strict_decode64(pack(data)).bytesize
37 (1.0 - compressed.fdiv(original)).round(4)
38 end
39end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping stream writes in begin/ensure guarantees the gzip footer is flushed even if writing fails.
- 2Base64 turns raw binary gzip output into a safe transportable string for JSON, URLs, or headers.
- 3Rescuing library-specific errors lets you present a single, meaningful failure to callers.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/compress-and-encode-payloads-in-ruby-explained-ruby-1317/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.