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
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 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.