Skip to content

Instantly share code, notes, and snippets.

@qzio
Created May 19, 2010 16:02
Show Gist options
  • Save qzio/406470 to your computer and use it in GitHub Desktop.
Save qzio/406470 to your computer and use it in GitHub Desktop.
def sanitize_xml(str)
replaces = [
["<","&lt;"],
[">","&gt;"],
["\"","&quot;"],
["\'","&apos;"],
["&","&amp;"]
]
replaces.each{|e| str.gsub!(e[1],e[0]) }
replaces.reverse.each{|e| str.gsub!(e[0],e[1])}
str
end
describe "sanitize_xml(str)" do
it "should s/r & => &amp;" do
sanitize_xml("&").should eql("&amp;")
sanitize_xml("h&amp;h").should eql("h&amp;h")
end
it "should handle <" do
sanitize_xml("<").should eql("&lt;")
sanitize_xml("h&lt;h").should eql("h&lt;h")
end
it "should handle >" do
sanitize_xml(">").should eql("&gt;")
sanitize_xml("h&gt;h").should eql("h&gt;h")
end
it "should handle \"" do
sanitize_xml("\"").should eql("&quot;")
sanitize_xml("h&quot;h").should eql("h&quot;h")
end
it "should handle '" do
sanitize_xml("'").should eql("&apos;")
sanitize_xml("h&apos;h").should eql("h&apos;h")
end
it "should handle multiples" do
sanitize_xml("one &amp; only &lt; < complex > string & replace").should(
eql("one &amp; only &lt; &lt; complex &gt; string &amp; replace")
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment