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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A dedicated scope object plus its binding controls exactly which names an ERB template can reference.
  2. 2method_missing paired with respond_to_missing? cleanly exposes hash entries as if they were real methods.
  3. 3Catching NameError lets you convert cryptic runtime failures into a meaningful, domain-specific error.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A safe ERB template renderer in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code