Class: ActiveSupport::JSON::Encoding::JSONGemEncoder

Inherits:
Object
  • Object
show all
Defined in:
activesupport/lib/active_support/json/encoding.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ JSONGemEncoder

Returns a new instance of JSONGemEncoder.



74
75
76
# File 'activesupport/lib/active_support/json/encoding.rb', line 74

def initialize(options = nil)
  @options = options || {}
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



72
73
74
# File 'activesupport/lib/active_support/json/encoding.rb', line 72

def options
  @options
end

Instance Method Details

#encode(value) ⇒ Object

Encode the given object into a JSON string



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'activesupport/lib/active_support/json/encoding.rb', line 79

def encode(value)
  unless options.empty?
    value = value.as_json(options.dup.freeze)
  end
  json = stringify(jsonify(value))

  return json unless @options.fetch(:escape, true)

  # Rails does more escaping than the JSON gem natively does (we
  # escape \u2028 and \u2029 and optionally >, <, & to work around
  # certain browser problems).
  json.force_encoding(::Encoding::BINARY)
  if @options.fetch(:escape_html_entities, Encoding.escape_html_entities_in_json)
    json.gsub!(ESCAPE_REGEX_WITH_HTML_ENTITIES, ESCAPED_CHARS)
  else
    json.gsub!(ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS)
  end
  json.force_encoding(::Encoding::UTF_8)
end