Created
April 15, 2013 15:44
-
-
Save reconbot/5389058 to your computer and use it in GitHub Desktop.
until the built in json_escape is worthwhile https://github.com/rails/rails/pull/6094
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def html_escape_json(json_string) | |
unsafe_chars = { | |
'<' => '\\u003c', | |
'>' => '\\u003e', | |
'&' => '\\u0026', | |
'=' => '\\u003d', | |
'\'' => '\\u0027' | |
} | |
unsafe_regex = /[<>&=']/ | |
unless json_string.is_a?(String) | |
return nil | |
end | |
result = json_string.gsub(unsafe_regex, unsafe_chars) | |
result.html_safe? ? result : result.html_safe | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe "html_escape_json" do | |
it "replaces unsafe characters with Unicode equivalents" do | |
unsafe_string = "a<b>c&d=e'f" | |
escaped_string = 'a\\u003cb\\u003ec\\u0026d\\u003de\\u0027f' | |
html_escape_json(unsafe_string).should eq(escaped_string) | |
end | |
it "returns an html safe string" do | |
html_escape_json("<>&='\"").should be_html_safe | |
html_escape_json("<>&='\"".html_safe).should be_html_safe | |
end | |
it "does not tolerate things that aren't strings" do | |
html_escape_json(4).should be_nil | |
end | |
it "kills script tags" do | |
html_escape_json('<script></script>'.to_json).should eq('"\\u003cscript\\u003e\\u003c/script\\u003e"') | |
html_escape_json('<script></script>'.to_json).should_not match('</script>') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment