Skip to content

Commit 9061627

Browse files
committed
Skip JSON escaping when writing into JSON columns
This extra escaping is only needed if the JSON end up included in a `<script>` tag, so entirely unnecessary when writing into a database column.
1 parent 8be58ff commit 9061627

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

activerecord/lib/active_record/coders/json.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
# frozen_string_literal: true
22

3+
require "active_support/json"
4+
35
module ActiveRecord
46
module Coders # :nodoc:
57
class JSON # :nodoc:
6-
def initialize(options = {})
7-
@options = options
8+
DEFAULT_OPTIONS = { escape: false }.freeze
9+
10+
def initialize(options = nil)
11+
@options = options ? DEFAULT_OPTIONS.merge(options) : DEFAULT_OPTIONS
12+
@encoder = ActiveSupport::JSON::Encoding.json_encoder.new(options)
813
end
914

1015
def dump(obj)
11-
ActiveSupport::JSON.encode(obj)
16+
@encoder.encode(obj)
1217
end
1318

1419
def load(json)

activerecord/lib/active_record/type/json.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# frozen_string_literal: true
22

3+
require "active_support/json"
4+
35
module ActiveRecord
46
module Type
57
class Json < ActiveModel::Type::Value
@@ -14,8 +16,10 @@ def deserialize(value)
1416
ActiveSupport::JSON.decode(value) rescue nil
1517
end
1618

19+
JSON_ENCODER = ActiveSupport::JSON::Encoding.json_encoder.new(escape: false)
20+
1721
def serialize(value)
18-
ActiveSupport::JSON.encode(value) unless value.nil?
22+
JSON_ENCODER.encode(value) unless value.nil?
1923
end
2024

2125
def changed_in_place?(raw_old_value, new_value)

0 commit comments

Comments
 (0)