hoodwink.d enhanced


Builder Singleton Hacks #

by why in inspect

Those tinkling chimes you hear mean it’s time on RedHanded for special thanks to Jim Weirich for his Builder. You see that organ grinder down on the corner who takes those rolls of Ruby and out plays elegant XML? That’s Builder.

Previously mentioned in The Best of method_missing. At present, I’m going to hand out a few singletons, which are the only additions I’ve ever needed to plain Builder.

Hack #1: Custom Tag Methods

I’ve been following Jim’s lead on adding helpful methods to Builder. I’m adding custom tag methods with a bang at the end. This way, I can still access the method_missing hook and the bang indicate ”your attention to this customization, please” rather than ”invade + decimate” as commonly thought.

 xm = Builder::XmlMarkup.new( :target => STDOUT, :indent => 2 )
 class << xm
   def date!( t )
     date :month => t.month, :day => t.day, :year => t.year

The above receives a timestamp and builds a date tag based on the timestamp.

 xm.entry do
   xm.author "_why" 
   xm.date! Time.now
   xm.title "Builder Singleton Hacks" 

Hack #2: Encoding Non-printables

The only major feature lacking in Builder is encoding on non-printable characters. Well, encoding in general. Here’s a quick fix for LATIN-1 ASCII.

 class << xm
   ELIMINATE = /[\x00-\x08\x0e-\x1f]/
   UNPRINTABLE = /[\x7f-\xff]/
   def _escape(text)
     gsub(%r{&}, '&amp;').
     gsub(%r{<}, '&lt;').
     gsub(%r{>}, '&gt;').
     gsub(ELIMINATE, '').
     gsub(UNPRINTABLE) do |str|
       "&\##{ str[0] };" 

I’ll be needing a UTF-8 version soon, so I’ll update this entry when the time comes.

said on 17 Feb 2005 at 16:45

My GenX4r library has a similar builder class that will automatically do all the encoding for you via the GenX library.

said on 17 Feb 2005 at 17:22

What about a validating version of the same metaphor. I’ve been considering writing a library that would do this, take an arbitrary CFG as input, then let you build instances of the grammar validating. No more invalid html generation, no more sql injection attacts, etc. Going the other way, taking input and outputting a tree of objects strikes me as a very useful general mechanism as well.

Comments are closed for this entry.