123456789_123456789_123456789_123456789_123456789_

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

Do not use. This class is for internal use only.
Relationships & Source Files
Inherits: Object
Defined in: activesupport/lib/active_support/json/encoding.rb

Class Method Summary

Instance Attribute Summary

Instance Method Summary

Constructor Details

.new(options = nil) ⇒ JSONGemEncoder

[ GitHub ]

  
# File 'activesupport/lib/active_support/json/encoding.rb', line 32

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

Instance Attribute Details

#options (readonly)

[ GitHub ]

  
# File 'activesupport/lib/active_support/json/encoding.rb', line 30

attr_reader :options

Instance Method Details

#encode(value)

Encode the given object into a ::ActiveSupport::JSON string

[ GitHub ]

  
# File 'activesupport/lib/active_support/json/encoding.rb', line 37

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

  # Rails does more escaping than the JSON gem natively does (we
  # escape \u2028 and \u2029 and optionally >, <, & to work around
  # certain browser problems).
  if @options.fetch(:escape_html_entities, Encoding.escape_html_entities_in_json)
    json.gsub!(">", '\u003e')
    json.gsub!("<", '\u003c')
    json.gsub!("&", '\u0026')
  end
  json.gsub!("\u2028", '\u2028')
  json.gsub!("\u2029", '\u2029')
  json
end

#jsonify(value) (private)

Convert an object into a “JSON-ready” representation composed of primitives like ::Hash, ::Array, ::String, ::Symbol, ::Numeric, and true+/false/+nil. Recursively calls #as_json to the object to recursively build a fully JSON-ready object.

This allows developers to implement #as_json without having to worry about what base types of objects they are allowed to return or having to remember to call #as_json recursively.

Note: the #options hash passed to object.to_json is only passed to object.as_json, not any of this method’s recursive #as_json calls.

[ GitHub ]

  
# File 'activesupport/lib/active_support/json/encoding.rb', line 70

def jsonify(value)
  case value
  when String, Integer, Symbol, nil, true, false
    value
  when Numeric
    value.as_json
  when Hash
    result = {}
    value.each do |k, v|
      k = k.to_s unless Symbol === k || String === k
      result[k] = jsonify(v)
    end
    result
  when Array
    value.map { |v| jsonify(v) }
  else
    jsonify value.as_json
  end
end

#stringify(jsonified) (private)

Encode a “jsonified” Ruby data structure using the ::ActiveSupport::JSON gem

[ GitHub ]

  
# File 'activesupport/lib/active_support/json/encoding.rb', line 91

def stringify(jsonified)
  ::JSON.generate(jsonified, quirks_mode: true, max_nesting: false)
end