ruby
45 lines · 10 steps
A safe ERB template renderer in Ruby
Wrapping ERB with a scoped binding turns local hash keys into template variables and missing ones into clear errors.
Explained by
highlit
1require "erb"
2
3class TemplateRenderer
4 class MissingVariableError < StandardError; end
5
6 def initialize(template, trim_mode: "-")
7 @template = template
8 @erb = ERB.new(template, trim_mode: trim_mode)
9 @erb.filename = "(template)"
10 end
11
12 def self.render_file(path, locals = {})
13 new(File.read(path)).render(locals)
14 end
15
16 def render(locals = {})
17 scope = Scope.new(locals)
18 @erb.result(scope.binding_context)
19 rescue NameError => e
20 raise MissingVariableError, "undefined template variable: #{e.name}"
21 end
22
23 class Scope
24 def initialize(locals)
25 @locals = locals.transform_keys(&:to_sym)
26 end
27
28 def binding_context
29 binding
30 end
31
32 def method_missing(name, *args)
33 return @locals.fetch(name) if @locals.key?(name)
34 super
35 end
36
37 def respond_to_missing?(name, include_private = false)
38 @locals.key?(name) || super
39 end
40
41 def h(text)
42 ERB::Util.html_escape(text)
43 end
44 end
45end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A dedicated scope object plus its binding controls exactly which names an ERB template can reference.
- 2method_missing paired with respond_to_missing? cleanly exposes hash entries as if they were real methods.
- 3Catching NameError lets you convert cryptic runtime failures into a meaningful, domain-specific error.
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/a-safe-erb-template-renderer-in-ruby-explained-ruby-f0ec/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.