From e9534445f8c474a31798790fc8e6c3b9d50b3065 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Wed, 24 May 2023 16:19:05 -0400 Subject: [PATCH] feat: introduce Rails::HTML::Sanitizer.best_supported_vendor so that callers don't need to check `html5_support?` to choose the best parser available. --- CHANGELOG.md | 5 ++++- lib/rails/html/sanitizer.rb | 4 ++++ test/rails_api_test.rb | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 811c8d9..1d2a6ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` @@ -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. diff --git a/lib/rails/html/sanitizer.rb b/lib/rails/html/sanitizer.rb index a6c81f1..b3712a7 100644 --- a/lib/rails/html/sanitizer.rb +++ b/lib/rails/html/sanitizer.rb @@ -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 = {}) diff --git a/test/rails_api_test.rb b/test/rails_api_test.rb index 4995fef..9bc1107 100644 --- a/test/rails_api_test.rb +++ b/test/rails_api_test.rb @@ -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)