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.

3 comments:

  1. Anonymous5:52 PM

    The function I wrote in APL, with {{ }} as the delimiters, has a creation timestamp of 19940417. Did Ruby even exist then?

    ReplyDelete
  2. Anonymous10:33 PM

    I honestly have no idea when it was created. I didn't start using it until about a year ago. This article has it listed as being created in 1993.

    ReplyDelete
  3. I did this for Java: JCite. Not only has it changed the quality of my docs, but it has affected the way I work. I have described this in a longish article:

    http://arrenbrecht.ch/articles/SourceCiting.htm

    ReplyDelete

Note: Only a member of this blog may post a comment.