Skip to content

Commit

Permalink
feat: introduce Rails::HTML::Sanitizer.best_supported_vendor
Browse files Browse the repository at this point in the history
so that callers don't need to check `html5_support?` to choose the
best parser available.
  • Loading branch information
flavorjones committed May 24, 2023
1 parent 5419017 commit e953444
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## 1.6.0.rc1 / 2023-05-24

* Sanitizers that use an HTML5 parser are now available on platforms supported by
* HTML5 standards-compliant sanitizers are now available on platforms supported by
Nokogiri::HTML5. These are available as:

- `Rails::HTML5::FullSanitizer`
Expand All @@ -13,6 +13,9 @@
Note that for symmetry `Rails::HTML4::Sanitizer` is also added, though its behavior is identical
to the vendor class methods on `Rails::HTML::Sanitizer`.

Users may call `Rails::HTML::Sanitizer.best_supported_vendor` to get back the HTML5 vendor if it's
supported, else the legacy HTML4 vendor.

*Mike Dalessio*

* Module namespaces have changed, but backwards compatibility is provided by aliases.
Expand Down
4 changes: 4 additions & 0 deletions lib/rails/html/sanitizer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ def html5_support?

@html5_support = Loofah.respond_to?(:html5_support?) && Loofah.html5_support?
end

def best_supported_vendor
html5_support? ? Rails::HTML5::Sanitizer : Rails::HTML4::Sanitizer
end
end

def sanitize(html, options = {})
Expand Down
14 changes: 14 additions & 0 deletions test/rails_api_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ def test_html_scrubber_class_names
assert(Rails::Html::Sanitizer)
end

def test_best_supported_vendor_when_html5_is_not_supported_returns_html4
Rails::HTML::Sanitizer.stub(:html5_support?, false) do
assert_equal(Rails::HTML4::Sanitizer, Rails::HTML::Sanitizer.best_supported_vendor)
end
end

def test_best_supported_vendor_when_html5_is_supported_returns_html5
skip("no HTML5 support on this platform") unless Rails::HTML::Sanitizer.html5_support?

Rails::HTML::Sanitizer.stub(:html5_support?, true) do
assert_equal(Rails::HTML5::Sanitizer, Rails::HTML::Sanitizer.best_supported_vendor)
end
end

def test_html4_sanitizer_alias_full
assert_equal(Rails::HTML4::FullSanitizer, Rails::HTML::FullSanitizer)
assert_equal("Rails::HTML4::FullSanitizer", Rails::HTML::FullSanitizer.name)
Expand Down

0 comments on commit e953444

Please sign in to comment.