Skip to content

Instantly share code, notes, and snippets.

@henrik
Created September 7, 2009 20:41
Show Gist options
  • Save henrik/182555 to your computer and use it in GitHub Desktop.
Save henrik/182555 to your computer and use it in GitHub Desktop.
Make Ruby's Builder default XML data to CDATA and not bork numbers.
# Make Builder default to CDATA and not bork numbers.
# By Henrik Nyh <http://henrik.nyh.se> 2009-08-07 under the MIT license.
require "rubygems"
require "builder"
xml_1 = Builder::XmlMarkup.new
xml_2 = Builder::XmlMarkup.new
# Override Builder so CDATA is used by default to escape text, and with no whitespace
# around it. Doesn't bork numbers like _cdata!_ does.
def xml_2._escape(text)
(text && caller[1].inspect.include?(%{`method_missing'})) ? "<![CDATA[#{text}]]>" : text
end
puts xml_1.Foo "bar & baz" # => <Foo>bar &amp; baz</Foo>
puts xml_2.Foo "bar & baz" # => <Foo><![CDATA[bar & baz]]></Foo>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment