Stumbled Across an Apple Leopard REXML Bug
While hacking away I came across a little bug in Apple’s version of REXML, so here’s a quick fix to get around it.
Just in case any of you wonder why when you use REXML’s write method on ruby 1.8.6 (2007-09-24 patchlevel 111) [universal-darwin9.0] and possibly other versions, you get errors, it’s a bug in Apple’s REXML library. See this:
def write(writer=$stdout, indent=-1, transitive=false, ie_hack=false)
Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
formatter = if indent > -1
if transitive
REXML::Formatters::Transitive.new( indent, ie_hack )
else
REXML::Formatters::Pretty.new( indent, ie_hack )
end
else
REXML::Formatters::Default.new( ie_hack )
end
formatter.write( self, output )
end
As you can see, the method sets a local variable of ‘writer’ in the method arguments, however at the bottom it uses ‘output’. A simple change of the bottom line fixes it:
formatter.write( self, writer )
For those who requested it, here’s how to use the formatter:
# I want to create a REXML document to output
require "rexml/document"
# Make a pretty formatter
formatter = REXML::Formatters::Pretty.new( 2 )
# Create some silly xml example
xml = REXML::Document.new '<moo>RAR!</moo>'
# Write to STDOUT
formatter.write( xml, $stdout )
# Write to file
xml_file = File.open( "some_file.xml", "a+" )
formatter.write( xml, xml_file )