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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Defining encode_with and init_with lets a class dump and rebuild itself through YAML instead of relying on default instance-variable dumping.
  2. 2safe_load with permitted_classes prevents arbitrary object instantiation from untrusted YAML, a common deserialization attack vector.
  3. 3Pairing a custom tag on dump with a whitelist on load keeps the round-trip both explicit and safe.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Custom YAML serialization in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code