1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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
This commit is contained in:
Sean Doyle 2020-11-26 17:52:26 -05:00
parent f75546891a
commit d2e07395b3
2 changed files with 3 additions and 0 deletions

View file

@ -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

View file

@ -130,6 +130,7 @@ class TagHelperTest < ActionView::TestCase
tag.p("<script>evil_js</script>")
assert_equal "<p><script>evil_js</script></p>",
tag.p("<script>evil_js</script>", escape_attributes: false)
assert_equal '<input pattern="\w+">', tag.input(pattern: /\w+/)
end
def test_tag_builder_nested