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::JSONstring. - #jsonify(value) private
-
#stringify(jsonified)
private
Encode a “jsonified” Ruby data structure using the
::ActiveSupport::JSONgem.
Constructor Details
.new(options = nil) ⇒ JSONGemEncoder
# File 'activesupport/lib/active_support/json/encoding.rb', line 78
def initialize( = nil) @options = || {} end
Instance Attribute Details
#options (readonly)
[ GitHub ]# File 'activesupport/lib/active_support/json/encoding.rb', line 76
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 83
def encode(value) unless .empty? value = value.as_json(.dup.freeze) end json = stringify(jsonify(value)) return json unless @options.fetch(:escape, true) json.force_encoding(::Encoding::BINARY) if @options.fetch(:escape_html_entities, Encoding.escape_html_entities_in_json) if Encoding.escape_js_separators_in_json json.gsub!(FULL_ESCAPE_REGEX, ESCAPED_CHARS) else json.gsub!(HTML_ENTITIES_REGEX, ESCAPED_CHARS) end elsif Encoding.escape_js_separators_in_json json.gsub!(JS_SEPARATORS_REGEX, 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+/. 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 118
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
# File 'activesupport/lib/active_support/json/encoding.rb', line 143
def stringify(jsonified) ::JSON.generate(jsonified) end