ruby
30 lines · 6 steps
Interpolating templates with dotted keys in Ruby
A small class replaces {{a.b}} placeholders by walking nested hashes, with an optional strict mode for missing keys.
Explained by
highlit
1class TemplateInterpolator
2 PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
3
4 def initialize(strict: false)
5 @strict = strict
6 end
7
8 def render(template, context)
9 template.gsub(PLACEHOLDER) do
10 key = Regexp.last_match(1)
11 value = resolve(key, context)
12
13 if value.nil?
14 raise KeyError, "missing value for {{#{key}}}" if @strict
15 ""
16 else
17 value.to_s
18 end
19 end
20 end
21
22 private
23
24 def resolve(key, context)
25 key.split(".").reduce(context) do |scope, segment|
26 break nil unless scope.respond_to?(:[])
27 scope[segment] || scope[segment.to_sym]
28 end
29 end
30end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A capture group inside a regex passed to `gsub` lets each match drive its own replacement logic.
- 2Folding over the segments of a dotted key turns nested lookups into a single traversal that bails out safely.
- 3A strict flag lets one method serve both lenient rendering and fail-fast validation.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
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
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
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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/interpolating-templates-with-dotted-keys-in-ruby-explained-ruby-abef/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.