Created
August 22, 2008 18:21
-
-
Save jqr/6831 to your computer and use it in GitHub Desktop.
Ruby String#to_json with support for html encoding and decoding
This file contains hidden or 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
# 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\": \"</script>\".unescapeHTML()}" |
This file contains hidden or 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
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