Skip to content

Commit

Permalink
Merge pull request rails#51272 from Resonious/json-html-escape-option
Browse files Browse the repository at this point in the history
Add escape_html_entities option to JSON encoder
  • Loading branch information
byroot authored Aug 11, 2024
2 parents bd24e3d + bdbc888 commit 8ebd0a4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
16 changes: 16 additions & 0 deletions activesupport/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
* Add `escape_html_entities` option to `ActiveSupport::JSON.encode`.

This allows for overriding the global configuration found at
`ActiveSupport.escape_html_entities_in_json` for specific calls to `to_json`.

This should be usable from controllers in the following manner:
```ruby
class MyController < ApplicationController
def index
render json: { hello: "world" }, escape_html_entities: false
end
end
```

*Nigel Baillie*

* Raise when using key which can't respond to `#to_sym` in `EncryptedConfiguration`.
As is the case when trying to use an Integer or Float as a key, which is unsupported.
Expand Down
3 changes: 2 additions & 1 deletion activesupport/lib/active_support/json/encoding.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class JSONGemEncoder # :nodoc:

def initialize(options = nil)
@options = options || {}

end

# Encode the given object into a JSON string
Expand All @@ -43,7 +44,7 @@ def encode(value)
# Rails does more escaping than the JSON gem natively does (we
# escape \u2028 and \u2029 and optionally >, <, & to work around
# certain browser problems).
if Encoding.escape_html_entities_in_json
if @options.fetch(:escape_html_entities, Encoding.escape_html_entities_in_json)
json.gsub!(">", '\u003e')
json.gsub!("<", '\u003c')
json.gsub!("&", '\u0026')
Expand Down
12 changes: 12 additions & 0 deletions activesupport/test/json/encoding_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ def test_hash_keys_encoding
ActiveSupport.escape_html_entities_in_json = false
end

def test_hash_keys_encoding_option
global_config = ActiveSupport.escape_html_entities_in_json

ActiveSupport.escape_html_entities_in_json = true
assert_equal "{\"<>\":\"<>\"}", ActiveSupport::JSON.encode({ "<>" => "<>" }, escape_html_entities: false)

ActiveSupport.escape_html_entities_in_json = false
assert_equal "{\"\\u003c\\u003e\":\"\\u003c\\u003e\"}", ActiveSupport::JSON.encode({ "<>" => "<>" }, escape_html_entities: true)
ensure
ActiveSupport.escape_html_entities_in_json = global_config
end

def test_utf8_string_encoded_properly
result = ActiveSupport::JSON.encode("€2.99")
assert_equal '"€2.99"', result
Expand Down

0 comments on commit 8ebd0a4

Please sign in to comment.