Module: ActiveSupport::JSON::Encoding

Defined in:
lib/active_support/json/encoding.rb

Overview

:nodoc:

Defined Under Namespace

Classes: CircularReferenceError

Constant Summary collapse

ESCAPED_CHARS =
{
"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002',
"\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005',
"\x06" => '\u0006', "\x07" => '\u0007', "\x0B" => '\u000B',
"\x0E" => '\u000E', "\x0F" => '\u000F', "\x10" => '\u0010',
"\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013',
"\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019',
"\x1A" => '\u001A', "\x1B" => '\u001B', "\x1C" => '\u001C',
"\x1D" => '\u001D', "\x1E" => '\u001E', "\x1F" => '\u001F',
"\010" =>  '\b',
"\f"   =>  '\f',
"\n"   =>  '\n',
"\r"   =>  '\r',
"\t"   =>  '\t',
'"'    =>  '\"',
'\\'   =>  '\\\\',
'>'    =>  '\u003E',
'<'    =>  '\u003C',
'&'    =>  '\u0026' }

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.escape_html_entities_in_jsonObject

Returns the value of attribute escape_html_entities_in_json.



50
51
52
# File 'lib/active_support/json/encoding.rb', line 50

def escape_html_entities_in_json
  @escape_html_entities_in_json
end

.escape_regexObject

Returns the value of attribute escape_regex.



49
50
51
# File 'lib/active_support/json/encoding.rb', line 49

def escape_regex
  @escape_regex
end

.use_standard_json_time_formatObject

If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format.



47
48
49
# File 'lib/active_support/json/encoding.rb', line 47

def use_standard_json_time_format
  @use_standard_json_time_format
end

Class Method Details

.encode(value, options = nil) ⇒ Object

Converts a Ruby object into a JSON string.



74
75
76
77
78
79
80
81
82
# File 'lib/active_support/json/encoding.rb', line 74

def encode(value, options = nil)
  options = {} unless Hash === options
  seen = (options[:seen] ||= [])
  raise CircularReferenceError, 'object references itself' if seen.include?(value)
  seen << value
  value.to_json(options)
ensure
  seen.pop
end

.escape(string) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/active_support/json/encoding.rb', line 61

def escape(string)
  string = string.dup.force_encoding(::Encoding::BINARY) if string.respond_to?(:force_encoding)
  json = string.
    gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
    gsub(/([\xC0-\xDF][\x80-\xBF]|
           [\xE0-\xEF][\x80-\xBF]{2}|
           [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
    s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
  }
  %("#{json}")
end