Skip to content

Commit d2ce0e9

Browse files
authored
Merge pull request rails#54503 from etiennebarrie/json-coder-fragment-native
Allow JSON::Fragment as a return value for as_json
2 parents e4c39ac + e2f2ad2 commit d2ce0e9

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

activesupport/lib/active_support/json/encoding.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ def encode(value)
8585
# to +object.as_json+, not any of this method's recursive +#as_json+
8686
# calls.
8787
def jsonify(value)
88+
return value if value.class.name == "JSON::Fragment"
8889
case value
8990
when String, Integer, Symbol, nil, true, false
9091
value
@@ -112,7 +113,7 @@ def stringify(jsonified)
112113

113114
if defined?(::JSON::Coder)
114115
class JSONGemCoderEncoder # :nodoc:
115-
JSON_NATIVE_TYPES = [Hash, Array, Float, String, Symbol, Integer, NilClass, TrueClass, FalseClass].freeze
116+
JSON_NATIVE_TYPES = [Hash, Array, Float, String, Symbol, Integer, NilClass, TrueClass, FalseClass, ::JSON::Fragment].freeze
116117
CODER = ::JSON::Coder.new do |value|
117118
json_value = value.as_json
118119
# 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)