Skip to content

Commit 8ebd0a4

Browse files
authored
Merge pull request rails#51272 from Resonious/json-html-escape-option
Add escape_html_entities option to JSON encoder
2 parents bd24e3d + bdbc888 commit 8ebd0a4

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

activesupport/CHANGELOG.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
* Add `escape_html_entities` option to `ActiveSupport::JSON.encode`.
2+
3+
This allows for overriding the global configuration found at
4+
`ActiveSupport.escape_html_entities_in_json` for specific calls to `to_json`.
5+
6+
This should be usable from controllers in the following manner:
7+
```ruby
8+
class MyController < ApplicationController
9+
def index
10+
render json: { hello: "world" }, escape_html_entities: false
11+
end
12+
end
13+
```
14+
15+
*Nigel Baillie*
16+
117
* Raise when using key which can't respond to `#to_sym` in `EncryptedConfiguration`.
218
319
As is the case when trying to use an Integer or Float as a key, which is unsupported.

activesupport/lib/active_support/json/encoding.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class JSONGemEncoder # :nodoc:
3131

3232
def initialize(options = nil)
3333
@options = options || {}
34+
3435
end
3536

3637
# Encode the given object into a JSON string
@@ -43,7 +44,7 @@ def encode(value)
4344
# Rails does more escaping than the JSON gem natively does (we
4445
# escape \u2028 and \u2029 and optionally >, <, & to work around
4546
# certain browser problems).
46-
if Encoding.escape_html_entities_in_json
47+
if @options.fetch(:escape_html_entities, Encoding.escape_html_entities_in_json)
4748
json.gsub!(">", '\u003e')
4849
json.gsub!("<", '\u003c')
4950
json.gsub!("&", '\u0026')

activesupport/test/json/encoding_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,18 @@ def test_hash_keys_encoding
5959
ActiveSupport.escape_html_entities_in_json = false
6060
end
6161

62+
def test_hash_keys_encoding_option
63+
global_config = ActiveSupport.escape_html_entities_in_json
64+
65+
ActiveSupport.escape_html_entities_in_json = true
66+
assert_equal "{\"<>\":\"<>\"}", ActiveSupport::JSON.encode({ "<>" => "<>" }, escape_html_entities: false)
67+
68+
ActiveSupport.escape_html_entities_in_json = false
69+
assert_equal "{\"\\u003c\\u003e\":\"\\u003c\\u003e\"}", ActiveSupport::JSON.encode({ "<>" => "<>" }, escape_html_entities: true)
70+
ensure
71+
ActiveSupport.escape_html_entities_in_json = global_config
72+
end
73+
6274
def test_utf8_string_encoded_properly
6375
result = ActiveSupport::JSON.encode("€2.99")
6476
assert_equal '"€2.99"', result

0 commit comments

Comments
 (0)