Class: ActiveSupport::JSON::Encoding::JSONGemCoderEncoder
- Defined in:
- lib/active_support/json/encoding.rb
Overview
:nodoc:
Constant Summary collapse
- JSON_NATIVE_TYPES =
[Hash, Array, Float, String, Symbol, Integer, NilClass, TrueClass, FalseClass, ::JSON::Fragment].freeze
- CODER =
::JSON::Coder.new do |value, is_key| json_value = value.as_json # Keep compatibility by calling to_s on non-String keys next value.to_s if is_key && !(String === json_value) # Handle objects returning self from as_json if json_value.equal?(value) next ::JSON::Fragment.new(::JSON.generate(json_value)) end # Handle objects not returning JSON-native types from as_json count = 5 until JSON_NATIVE_TYPES.include?(json_value.class) raise SystemStackError if count == 0 json_value = json_value.as_json count -= 1 end json_value end
Instance Method Summary collapse
-
#encode(value) ⇒ Object
Encode the given object into a JSON string.
-
#initialize(options = nil) ⇒ JSONGemCoderEncoder
constructor
A new instance of JSONGemCoderEncoder.
Constructor Details
#initialize(options = nil) ⇒ JSONGemCoderEncoder
Returns a new instance of JSONGemCoderEncoder.
173 174 175 176 177 178 179 180 181 182 |
# File 'lib/active_support/json/encoding.rb', line 173 def initialize( = nil) if = .dup @escape = .delete(:escape) { true } = .freeze else @escape = true = {}.freeze end end |
Instance Method Details
#encode(value) ⇒ Object
Encode the given object into a JSON string
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/active_support/json/encoding.rb', line 185 def encode(value) value = value.as_json() unless .empty? json = CODER.dump(value) return json unless @escape json.force_encoding(::Encoding::BINARY) if .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 |