Class: ActiveSupport::JSON::Encoding::JSONGemEncoder
Relationships & Source Files | |
Inherits: | Object |
Defined in: | activesupport/lib/active_support/json/encoding.rb |
Class Method Summary
- .new(options = nil) ⇒ JSONGemEncoder constructor
Instance Attribute Summary
- #options readonly
Instance Method Summary
-
#encode(value)
Encode the given object into a
::ActiveSupport::JSON
string. - #jsonify(value) private
-
#stringify(jsonified)
private
Encode a “jsonified” Ruby data structure using the
::ActiveSupport::JSON
gem.
Constructor Details
.new(options = nil) ⇒ JSONGemEncoder
# File 'activesupport/lib/active_support/json/encoding.rb', line 32
def initialize( = nil) @options = || {} end
Instance Attribute Details
#options (readonly)
[ GitHub ]# File 'activesupport/lib/active_support/json/encoding.rb', line 30
attr_reader :
Instance Method Details
#encode(value)
Encode the given object into a ::ActiveSupport::JSON
string
# File 'activesupport/lib/active_support/json/encoding.rb', line 37
def encode(value) unless .empty? value = value.as_json( .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+/
. Recursively calls false
/+nil#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.
# 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
# File 'activesupport/lib/active_support/json/encoding.rb', line 91
def stringify(jsonified) ::JSON.generate(jsonified, quirks_mode: true, max_nesting: false) end