Skip to content

Instantly share code, notes, and snippets.

@jqr
Created August 22, 2008 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqr/6831 to your computer and use it in GitHub Desktop.
Save jqr/6831 to your computer and use it in GitHub Desktop.
Ruby String#to_json with support for html encoding and decoding
# When inserting Javascript in HTML there is a a problem with the
# </script> end tag.
#
# Standard Javascript escaping works fine for most strings, but the
# browser interprets </script> before Javascript is being parsed, so
# it needs to be HTML escaped while the browser is parsing, and then
# unescaped as Javascript parses it.
# Regular to_json
{ 'key' => '</script>' }.to_json
# => "{\"key\": \"</script>\"}"
# HTML escaped to_json with unescapeHTML() as the JS side decoder
{ 'key' => '</script>' }.to_json(:html_encode => 'unescapeHTML()')
# => "{\"key\": \"&lt;/script&gt;\".unescapeHTML()}"
class String
def to_json_with_html_encoding(options = nil)
if options.is_a?(Hash) && options[:html_encode]
ERB::Util::h(self).to_json_without_html_encoding + '.' + options[:html_encode]
else
to_json_without_html_encoding
end
end
end
String.alias_method_chain :to_json, :html_encoding
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment