So we can see all that’s needed to create a new instance of ERB is the template in the form of a String, and then call result in order to render the template and interpolate any variables.
Notice that name is a variable in the top level context of self.
The binding is a pointer to a set of local variables. If no binding is given, the top level binding will be used, which is why <%= name %> gets evaluated as “Gareth” in the above example.
We can pass a Binding object to ERB#render to access a different set of variables.
What I really wanted was a class that could return a rendered template itself.
First, I defined how I wanted to interact with the class and sketched a template of the public methods I’d need.
Setting up the data
After storing the name in an instance variable, the next step was picking the template to render. As we know, ERB itself takes the template string as an argument to initialize. We can pass this up the chain by calling super with the template. I set a default at the class level and allowed an option to be passed when creating a new instance of the class.
Now we need to interpolate the variables in to the template and render it. To make the API consistent with ERB, we’ll override ERB#result to always pass the binding as a parameter.
Now we can use the new class to render our template!