This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Builder Singleton Hacks
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
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
end
end
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"
end
Hack #2: Encoding Non-printables
The only major feature lacking in Builder is encoding on non-printable characters. Here’s a quick fix for LATIN-1 ASCII.
class << xm
ELIMINATE = /[\x00-\x08\x0e-\x1f]/
UNPRINTABLE = /[\x7f-\xff]/
def _escape(text)
text.
gsub(%r{&}, '&').
gsub(%r{<}, '<').
gsub(%r{>}, '>').
gsub(ELIMINATE, '').
gsub(UNPRINTABLE) do |str|
"&\##{ str[0] };"
end
end
end
I’ll be needing a UTF-8 version soon, so I’ll update this entry when the time comes.