Monday, June 26, 2006

Use erb to insert dynamic text

Tonight, I was writing up some new material and wanted to mix some examples with the text. I could have just pasted the code into the material; however, I wanted the material to update automatically if I updated the code. When working with Martin on his next book I got to experience the value in this practice first hand and it wasn't something I wanted to work without at this point.

So, I decided to use a similar tag system in my writing. When deciding on what syntax to use to delimit areas where I wanted code to execute I thought of the <% .. %> syntax common to .rhtml, .yaml, etc files. My first instinct was to use some type of description inside my delimiter and process the file based on the description. Then I realized, it would be easiest to simply express what I want to do by writing the valid ruby.

At this point I had a text file that contained small blocks of code surrounded by <%= %>. I could write a task that searches and evals all the code, but this seemed to be much better:
erb INPUT > OUTPUT
That's it, my output is now generated from the static text and the dynamic code that executes. I love it when the simplest thing that could possibly work just works.
Post a Comment