Skip to content

Commit 612d933

Browse files
etiennebarriebyroot
andcommitted
Allow JSON::Fragment as a return value for as_json
Instead of overriding to_json to return a piece of JSON to be directly embedded in the JSON document, we can now return a JSON::Fragment from as_json. Since both JSON::Coder and JSON::Fragment were shipped together in json 2.10.0, I didn't update the defined? guards. Co-authored-by: Jean Boussier <[email protected]>
1 parent 9621e59 commit 612d933

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

activesupport/lib/active_support/json/encoding.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def stringify(jsonified)
112112

113113
if defined?(::JSON::Coder)
114114
class JSONGemCoderEncoder # :nodoc:
115-
JSON_NATIVE_TYPES = [Hash, Array, Float, String, Symbol, Integer, NilClass, TrueClass, FalseClass].freeze
115+
JSON_NATIVE_TYPES = [Hash, Array, Float, String, Symbol, Integer, NilClass, TrueClass, FalseClass, ::JSON::Fragment].freeze
116116
CODER = ::JSON::Coder.new do |value|
117117
json_value = value.as_json
118118
# Handle objects returning self from as_json

activesupport/test/json/encoding_test_cases.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ def to_json(options = nil)
5656
end
5757
end
5858

59+
class CustomNumericFixed < Numeric
60+
def initialize(str)
61+
@str = str
62+
end
63+
64+
def as_json
65+
::JSON::Fragment.new(@str)
66+
end
67+
end
68+
5969
module EncodingTestCases
6070
TrueTests = [[ true, %(true) ]]
6171
FalseTests = [[ false, %(false) ]]
@@ -68,7 +78,8 @@ module EncodingTestCases
6878
[ BigDecimal("0.0") / BigDecimal("0.0"), %(null) ],
6979
[ BigDecimal("2.5"), %("#{BigDecimal('2.5')}") ],
7080
[ RomanNumeral.new("MCCCXXXVII"), %("MCCCXXXVII") ],
71-
[ [CustomNumeric.new("123")], %([123]) ]
81+
[ [CustomNumeric.new("123")], %([123]) ],
82+
[ [CustomNumericFixed.new("123")], %([123]) ],
7283
]
7384

7485
StringTests = [[ "this is the <string>", %("this is the \\u003cstring\\u003e")],

0 commit comments

Comments
 (0)