Chapter 15
Templating Output with ERB

We’ve looked at writing data either in an unformatted way or into standard formats like XML, JSON, and CSV. Sometimes, though, we need to conform to more complex or more unusual formats, ones that don’t have ready-made libraries but that are nevertheless still text formats.

For example, imagine that we want to generate a financial report for a bar, outlining the purchases made by the bar in the past month. We want the final output to look something like this:

 
The Bistro Illegal
 
Sector RT 74
 
Lazgar Beta
 
 
Purchase ledger, October 2014
 
 
Generated: 4 October 2014, 12:49pm
 
 
Product Units Price
 
 
Ol' Janx Spirit 282 $27,918.00
 
Eau de Santraginus V 300 $600.00
 
Arcturan Mega-Gin 150 $7,500.00
 
Fallian Marsh Gas 1,000 $2,000.00
 
Qalactin Hypermint Extract 25 $500.00
 
Algolian Suntiger, teeth of 300 $30,000.00
 
Zamphuor 3 $120.00
 
Olives 200 $24.00
 
 
Total $68,662.00

This isn’t too complex. It’s something that we could achieve with some standard puts and printf statements, as we did in Chapter 12, Standard Output and Standard Error. But this leaves us in a state where we’re combining the formatting of our output with the logic of how the data is being generated. We’re combining business logic with presentation logic, which will make things harder to maintain in the long run. If you’ve done any web development, especially in an MVC framework such as Rails, this principle is likely to be familiar to you: there, we keep our model logic separate from our view logic.

When things get to this point, we can help ourselves out by using a templating system to split out the presentation side of things. This will allow us to calculate the values in one place, and in another define the formatting of our final output. Changing one of these things won’t require us to change the other, and when trying to make such a change we won’t have to wade through irrelevant information to get to the parts we want to modify.

Using a templating system will allow us to create significantly more complex output than we would otherwise be able to. Looping over collections, using branching to alter our output based on particular conditions—we have all the power of a programming language from within our templates.

Ruby comes with a powerful templating system included in its standard library. It’s called ERB—short for Embedded Ruby—and it allows us to embed Ruby code inside of other text. That text might be HTML if our output is for the web. It might be an email. Or it could just be a plain-text document intended for a person to read. The beauty of ERB is that we can use it to generate any sort of text output. Let’s take a look at how to use it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.244.94