Ruby for Programmers – Part 14: ERB My HTML!

And now for something completely different.

Let’s say you want to generate some HTML. Using interpolated strings is generally not a good idea as it can lead to unmaintainable code. The best way to handle this is through a templating engine, which is output text intermixed with code. Thankfully, Ruby itself contains it’s own built-in templating engine: ERB

‘binding’ is a special variable that is an object that contains the current variable scope. Yes, even scopes are objects that you can pass around. (Not recommended outside of template engines, as it messes with the garbage collector and may lead to memory leaks.)

There are three different tags to invoke:

The first allows one to write code before, and around, text. The second puts the result of code in the the output itself. The last is a way to write a comment. (You do write comments don’t you?)

So let’s add erb to our controller:

But that doesn’t really abstract that out enough to be useful. However, we can now put the text into different files, which is even better! We’re going to put the views into app/views/CONTROLLERNAME/ACTIONNAME.html.erb :

So as you can see in the controller, we’re pretty much doing the same thing, which means abstraction time and another new module: ActionController::ImplicitRender, which simply calls #render after the method is run:

And let’s add some more programmability with that:

This lets us pass some options and force a different type of render if we so please. In this case, it lets us give a specialized 404 error if the page id isn’t what we expect. You can render a text value and a status. But what if we wanted to render a different layout? Well all that, and more, is in the ActionView, a culmination of all the rendering points and more, in the next part.

As usual, working code examples are in my Github: https://github.com/ROFISH/ruby_for_programmers/tree/master/14