Blog An exploration of the art and
craft of software development

Builder and escaping values

Posted by Marty Haught on Sunday, March 09, 2008

I’ve been working a bit more with Builder in my Calendar extension that I hope to have the first alpha release on. I really like builder but I’ve run into a snag. I’m trying to generate a url such as this:

<a href="?date=2008-04-01" title="April">&#187;</a>

My first shot at creating this in builder was with this:

html.a("&#187;", :href => "?date=2008-04-01", :title => "April")

But that created this:

<a href="?date=2008-04-01" title="April">&amp;#187;</a>

Builder now escapes everything, including attributes, which is great except when you don’t want them escaped. Now the rdoc talks about how to get around this using the symbol hack such as this: :“NoEscape&”. So with this knowledge here was my next attempt.

html.a(:"&#187;", :href => "?date=2008-04-01", :title => "April")

Hmm, no soup.

<a:&#187; href="?date=2008-04-01" title="April"/>

Then I remembered there was another way to slip in a string into element’s body.

html.a(:href => "?date=2008-04-01", :title => "April") { |x| x << :"&#187;"}

That was only worse blowing up builder with this error:

can't convert Symbol into String

So I just tried getting rid of the : with this:

html.a(:href => "?date=2008-04-01", :title => "April") { |x| x << "&#187;"}

Finally, this got it. I’m guessing that the << operator in builder doesn’t do escaping. Sure enough after checking the rdoc, I was right:

  Append text to the output target without escaping any markup. May be used within the markup brakets as:

    builder.p { |x| x << "<br/>HI" }   #=>  <p><br/>HI</p>

  This is useful when using non-builder enabled software that generates strings. Just insert the string 
  directly into the builder without changing the inserted markup.

  It is also useful for stacking builder objects. Builders only use << to append to the target, so by 
  supporting this method/operation builders can use other builders as their targets.

Enjoy!

blog comments powered by Disqus