Skip to content

Commit 94e2c60

Browse files
etiennebarriebyroot
andcommitted
Add fast-path for Object#to_json(escape: false)
Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
1 parent 80827ca commit 94e2c60

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

activesupport/lib/active_support/json/encoding.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ class << self
4646
def encode(value, options = nil)
4747
if options.nil? || options.empty?
4848
Encoding.encode_without_options(value)
49+
elsif options == { escape: false }.freeze
50+
Encoding.encode_without_escape(value)
4951
else
5052
Encoding.json_encoder.new(options).encode(value)
5153
end
@@ -161,7 +163,14 @@ class JSONGemCoderEncoder # :nodoc:
161163

162164

163165
def initialize(options = nil)
164-
@options = options ? options.dup.freeze : {}.freeze
166+
if options
167+
options = options.dup
168+
@escape = options.delete(:escape) { true }
169+
@options = options.freeze
170+
else
171+
@escape = true
172+
@options = {}.freeze
173+
end
165174
end
166175

167176
# Encode the given object into a JSON string
@@ -170,7 +179,7 @@ def encode(value)
170179

171180
json = CODER.dump(value)
172181

173-
return json unless @options.fetch(:escape, true)
182+
return json unless @escape
174183

175184
# Rails does more escaping than the JSON gem natively does (we
176185
# escape \u2028 and \u2029 and optionally >, <, & to work around
@@ -206,11 +215,16 @@ class << self
206215
def json_encoder=(encoder)
207216
@json_encoder = encoder
208217
@encoder_without_options = encoder.new
218+
@encoder_without_escape = encoder.new(escape: false)
209219
end
210220

211221
def encode_without_options(value) # :nodoc:
212222
@encoder_without_options.encode(value)
213223
end
224+
225+
def encode_without_escape(value) # :nodoc:
226+
@encoder_without_escape.encode(value)
227+
end
214228
end
215229

216230
self.use_standard_json_time_format = true

0 commit comments

Comments
 (0)