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 50

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

Instance Attribute Details

#options (readonly)

[ GitHub ]

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

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 55

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).
  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

#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 87

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
    if defined?(::JSON::Fragment) && ::JSON::Fragment === value
      value
    else
      jsonify value.as_json
    end
  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 112

def stringify(jsonified)
  ::JSON.generate(jsonified)
end