ERB – text with holes for Ruby
Many programs write text that looks almost the same every time: an email, an invoice, a web page. Only a few places change – the name, the amount, the list. That is what templates are for, and in Ruby the best known is ERB, “Embedded Ruby”: Ruby embedded in text. ERB is part of the standard library; most pages of a Rails app are made from ERB templates.
require "erb"
template = ERB.new("Hello <%= name %>, here are <%= count %> strips of bacon.")
template.result_with_hash(name: "Chunky", count: 3)Everything between <%= and %> is Ruby; ERB works it out and puts the result in its place. ERB.new reads the template once, result_with_hash fills it with values – as often as you like, with new values each time. (Instead of a hash there is also result(binding): then the template sees the local variables of the place you call it from.)
Without the equals sign, <% … %>, the Ruby code only runs and writes nothing. That is how you build loops and conditions:
require "erb"
list = ERB.new(<<~TEXT, trim_mode: "-")
Shopping list:
<%- items.each do |item, qty| -%>
- <%= qty %> x <%= item %>
<%- end -%>
<%- if items.empty? -%>
(nothing)
<%- end -%>
TEXT
puts list.result_with_hash(items: { "Bacon" => 3, "Pretzel" => 2 })The loop each … end repeats the line in between for every item, and the if leaves out “(nothing)” while there is something on the list. And the minus signs? With trim_mode: "-", <%- swallows the indentation before it and -%> the line break after it. Without them every Ruby line would leave an empty line of text behind. Try it: delete the minus signs.
Web pages are text too, only with HTML. But careful when they contain what somebody else wrote:
require "erb"
comment = "<script>alert('All bacon is mine!')</script>"
puts ERB.new("<p><%= comment %></p>").result(binding)
puts ERB.new("<p><%= ERB::Util.h(comment) %></p>").result(binding)The first line is dangerous. A browser reads a <script> in it and runs it – a stranger's program, on your shop's page, with your customers' data. That is called cross-site scripting (XSS), one of the most common security holes on the web. ERB::Util.h (h for HTML) escapes the special characters: < becomes <, and the browser shows the characters instead of running them. The rule: everything that does not come from you goes through h. (Rails does that by itself.)
And this is how an ERB template becomes a page in the mini browser (lesson 53) – a lambda will do as a Rack app:
require "erb"
page = ERB.new(<<~HTML)
<h1>Chunky's shop</h1>
<ul>
<% goods.each do |name, price| %>
<li><%= ERB::Util.h(name) %>: <%= format("%.2f", price) %></li>
<% end %>
</ul>
HTML
shop = lambda do |_env|
html = page.result_with_hash(goods: { "Bacon" => 4.5, "Pretzel" => 2.0, "Cheese" => 6.25 })
[200, { "content-type" => "text/html" }, [html]]
end
show_browser shopNow a weakness of ERB: it knows nothing about HTML. To ERB the template is just text with holes. A tag closed wrongly, a forgotten quote – ERB does not notice, and the browser quietly repairs it, somehow. The mistake only shows when the page looks odd.
Herb by Marco Roth reads HTML and ERB together. It understands which tag opens where and where it closes, even across Ruby loops and conditions, and reports what does not fit:
install_gem "herb"
require "herb"
broken = "<div><%= name %></span>"
puts ERB.new(broken).result_with_hash(name: "Chunky")
result = Herb.parse(broken)
result.errors.each { |error| puts error.message }
result.success?ERB turns the broken template into <div>Chunky</span> without a murmur. Herb, on the other hand, finds two mistakes: the <div> is never closed, and the </span> had no opening tag. Each error also knows where it is (error.location).
On top of that Herb builds a tree from the template – a syntax tree, whose nodes are HTML elements and pieces of ERB:
puts Herb.parse("<b><%= name %></b>").value.inspectAn HTMLElementNode with its opening and closing tag, and inside it an ERBContentNode with the Ruby code. Herb's tools build on this tree: a linter that checks rules, a formatter, and help in the editor.
Herb pays off most in tests: a test that checks every template falls over as soon as somebody closes a tag wrongly – long before anyone sees it in the browser. With Minitest from lesson 111:
require "minitest"
class TemplatesTest < Minitest::Test
def test_the_list_is_whole
assert_empty Herb.parse("<ul><li><%= item %></li></ul>").errors
end
def test_the_picture
errors = Herb.parse('<img src="bacon.png"></img>').errors
assert_empty errors.map(&:message)
end
end
run_testsThe first test passes. The second fails, and the message says why: <img> is a void element, it has no content and so no </img> either. assert_empty errors.map(&:message) shows the messages themselves when it fails, not just that something was not empty.
Herb's parser is written in C. Here in the browser the same parser runs as WebAssembly, and the gem around it is the real one. At home: gem install herb (on Windows the install currently fails on a file with a question mark in its name – under WSL it works). The gem comes with the herb command: herb analyze app/views checks all the templates of a project, herb parse page.html.erb shows the tree. The linter and the formatter come through Node.js (npx @herb-tools/linter, npx @herb-tools/formatter), and with the Herb Language Server VS Code, Zed or Neovim show the mistakes while you type.
ShopTest that uses Herb.parse(shop_list) to check that it has no errors, and run it with run_tests. It fails – then repair shop_list until it passes.install_gem "herb"
require "herb"
require "minitest"
def shop_list
"<ul><% goods.each do |item| %><li><%= item %></span><% end %></ul>"
end
# Write a test ShopTest that checks with Herb that shop_list has no errors,
# and run it with run_tests - then repair shop_list.