Embedded Ruby for Code Generation (erb)
Code generation can be useful for dynamically generating static files based on a template. When we need this sort of functionality, we can turn to the erb standard library. ERB stands for Embedded Ruby, which is ultimately exactly what the library facilitates.
In the most basic case, a simple ERB template[23] might look like this:
require 'erb'
x = 42
template = ERB.new("The value of x is: <%= x %>")
puts template.result(binding)The resulting text looks like this:
The value of x is: 42
If you’ve not worked with ERB before, you may be wondering how this differs from ordinary string interpolation, such as this:
x = 42
puts "The value of x is: #{x}"The key difference to recognize here is the way the two strings are
evaluated. When we use string interpolation, our values are substituted
immediately. When we evaluate an ERB template, we do not actually evaluate
the expression inside the <%= ...
%> until we call ERB#result. That means that although this code
does not work at all:
string = "The value of x is: #{x}"
x = 42
puts stringthe following code will work without any problems:
require 'erb'
template = ERB.new("The value of x is: <%= x %>")
x = 42
puts template.result(binding)This is the main reason why ERB can be useful to us. We can write
templates ahead of time, referencing variables and methods that may not
exist yet, and then bind them just before rendering time using binding.
We can also include some logic in our files, to determine what should ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access