Thursday, July 16, 2009

Escaping XML in Ruby

Looked around and found this post from Sam Ruby that wrote the code to escape XML that was included in builder. Here is a short class I wrote to abstract out the XML escaping functionality, and be sure it is a string before calling to_xs on it.
require 'builder/xchar'
...    
    def self.x(input)
      # don't know if is string, so convert to string first, then to XML escaped text.
      return input.to_s.to_xs
    end
  end
...

If you were to call this method x you could call it like this for a quick way to escape:

...
some_xml = "#{x(variable_that_needs_escaping)}"
...

No comments: