ruby
44 lines · 7 steps
Custom YAML serialization in Ruby
How encode_with and init_with give a class full control over its YAML representation, and how safe_load reads it back.
Explained by
highlit
1require "yaml"
2require "date"
3
4class Money
5 attr_reader :cents, :currency
6
7 def initialize(cents:, currency: "USD")
8 @cents = cents
9 @currency = currency
10 end
11
12 def encode_with(coder)
13 coder.tag = "!money"
14 coder.map["cents"] = @cents
15 coder.map["currency"] = @currency
16 end
17
18 def init_with(coder)
19 @cents = coder.map.fetch("cents")
20 @currency = coder.map.fetch("currency", "USD")
21 end
22end
23
24Invoice = Struct.new(:number, :issued_on, :total, :line_items, keyword_init: true)
25
26class InvoiceRepository
27 PERMITTED = [Symbol, Date, Money, Invoice].freeze
28
29 def initialize(path)
30 @path = path
31 end
32
33 def save(invoices)
34 File.write(@path, YAML.dump(invoices))
35 end
36
37 def load
38 YAML.safe_load_file(
39 @path,
40 permitted_classes: PERMITTED,
41 aliases: true
42 )
43 end
44end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Defining encode_with and init_with lets a class dump and rebuild itself through YAML instead of relying on default instance-variable dumping.
- 2safe_load with permitted_classes prevents arbitrary object instantiation from untrusted YAML, a common deserialization attack vector.
- 3Pairing a custom tag on dump with a whitelist on load keeps the round-trip both explicit and safe.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 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/custom-yaml-serialization-in-ruby-explained-ruby-3845/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.