From d2e07395b3cbb6fb184797335bf0c1fa6edb5f38 Mon Sep 17 00:00:00 2001 From: Sean Doyle Date: Thu, 26 Nov 2020 17:52:26 -0500 Subject: [PATCH] ActionView: Serialize Regexp into HTML attribute When serializing a Regexp instance, encode the [Regexp#source][]. When encoding a value into a [pattern][] attribute from ERB/Ruby, declaring the String can be tedious. For example, one might attempt to encode `\w+` as `"\\\w+"`, but once serialized to the browser, that is not equivalent to the `"\w+"` HTML attribute. Instead, enable declaring Regexp and Regexp literals as attributes, and encoding them as their source String. [Regexp#source]: https://ruby-doc.org/core-2.7.2/Regexp.html#method-i-source [pattern]: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern --- actionview/lib/action_view/helpers/tag_helper.rb | 2 ++ actionview/test/template/tag_helper_test.rb | 1 + 2 files changed, 3 insertions(+) diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb index c22326dd0b..cdbfbaa80f 100644 --- a/actionview/lib/action_view/helpers/tag_helper.rb +++ b/actionview/lib/action_view/helpers/tag_helper.rb @@ -121,6 +121,8 @@ module ActionView when Array, Hash value = TagHelper.build_tag_values(value) if key.to_s == "class" value = escape ? safe_join(value, " ") : value.join(" ") + when Regexp + value = escape ? ERB::Util.unwrapped_html_escape(value.source) : value.source else value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s end diff --git a/actionview/test/template/tag_helper_test.rb b/actionview/test/template/tag_helper_test.rb index 01f8cb0d60..6c962bda21 100644 --- a/actionview/test/template/tag_helper_test.rb +++ b/actionview/test/template/tag_helper_test.rb @@ -130,6 +130,7 @@ class TagHelperTest < ActionView::TestCase tag.p("") assert_equal "

", tag.p("", escape_attributes: false) + assert_equal '', tag.input(pattern: /\w+/) end def test_tag_builder_nested