Skip to content

Commit 2761020

Browse files
etiennebarriebyroot
andcommitted
Update JSONGemCoderEncoder to handle non-String hash keys
Follow-up to a8a80e3. Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
1 parent 4e72506 commit 2761020

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

Gemfile.lock

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ GEM
311311
jmespath (1.6.2)
312312
jsbundling-rails (1.3.1)
313313
railties (>= 6.0.0)
314-
json (2.14.0)
314+
json (2.15.0)
315315
jwt (2.10.1)
316316
base64
317317
kamal (2.4.0)

activesupport/lib/active_support/json/encoding.rb

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -140,20 +140,17 @@ def stringify(jsonified)
140140
end
141141
end
142142

143-
if defined?(::JSON::Coder)
143+
# ruby/json 2.14.x yields non-String keys but doesn't let us know it's a key
144+
if defined?(::JSON::Coder) && !::JSON::VERSION.start_with?("2.14.")
144145
class JSONGemCoderEncoder # :nodoc:
145146
JSON_NATIVE_TYPES = [Hash, Array, Float, String, Symbol, Integer, NilClass, TrueClass, FalseClass, ::JSON::Fragment].freeze
146-
CODER = ::JSON::Coder.new do |value|
147+
CODER = ::JSON::Coder.new do |value, is_key|
147148
json_value = value.as_json
149+
# Keep compatibility by calling to_s on non-String keys
150+
next json_value.to_s if is_key
148151
# Handle objects returning self from as_json
149152
if json_value.equal?(value)
150-
if JSON_NATIVE_TYPES.include?(json_value.class)
151-
# If the callback is invoked for a native type,
152-
# it means it is hash keys, e.g. { 1 => true }
153-
next json_value.to_s
154-
else
155-
next ::JSON::Fragment.new(::JSON.generate(json_value))
156-
end
153+
next ::JSON::Fragment.new(::JSON.generate(json_value))
157154
end
158155
# Handle objects not returning JSON-native types from as_json
159156
count = 5
@@ -222,7 +219,7 @@ def encode_without_options(value) # :nodoc:
222219
self.use_standard_json_time_format = true
223220
self.escape_html_entities_in_json = true
224221
self.json_encoder =
225-
if defined?(::JSON::Coder)
222+
if defined?(JSONGemCoderEncoder)
226223
JSONGemCoderEncoder
227224
else
228225
JSONGemEncoder

0 commit comments

Comments
 (0)