Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activesupport/lib/active_support/json/encoders/string.rb

Revision 9238, 0.9 kB (checked in by rick, 1 month ago)

Add config.active_support.escape_html_entities_in_json to allow disabling of html entity escaping. [rick]

Line 
1 module ActiveSupport
2   module JSON
3     module Encoding
4       mattr_accessor :escape_regex
5
6       ESCAPED_CHARS = {
7         "\010" =>  '\b',
8         "\f"   =>  '\f',
9         "\n"   =>  '\n',
10         "\r"   =>  '\r',
11         "\t"   =>  '\t',
12         '"'    =>  '\"',
13         '\\'   =>  '\\\\',
14         '>'    =>  '\u003E',
15         '<'    =>  '\u003C',
16         '&'    =>  '\u0026'
17       }
18     end
19   end
20 end
21
22 ActiveSupport.escape_html_entities_in_json = true
23
24 class String
25   def to_json(options = nil) #:nodoc:
26     json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
27       ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
28     }
29     json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
30     json.gsub(/([\xC0-\xDF][\x80-\xBF]|
31              [\xE0-\xEF][\x80-\xBF]{2}|
32              [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
33       s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&')
34     } + '"'
35   end
36 end
Note: See TracBrowser for help on using the browser.