[ruby/erb] Respect ERB tag boundaries when detecting magic comments

https://github.com/ruby/erb/commit/934d51e24b
This commit is contained in:
ydah 2026-10-06 08:49:51 +09:00 committed by git
parent 8993cb5a3c
commit 28da13e768
3 changed files with 15 additions and 1 deletions

View File

@ -452,7 +452,7 @@ class ERB::Compiler # :nodoc:
attr_accessor :content
def detect_magic_comment(s, enc = nil)
re = @percent ? /\G(?:<%#(.*)%>|%#(.*)\n)/ : /\G<%#(.*)%>/
re = @percent ? /\G(?:<%#(.*?)%>|%#(.*)\n)/ : /\G<%#(.*?)%>/
frozen = nil
s.scan(re) do
comment = $+

View File

@ -595,6 +595,13 @@ EOS
end
end
def test_frozen_string_literal_after_encoding_comment
[nil, '%'].each do |trim_mode|
erb = @erb.new("<%# coding: utf-8 %><%# frozen_string_literal: true %><%= ''.frozen? %>", trim_mode: trim_mode)
assert_equal("true", erb.result)
end
end
def test_result_with_hash
erb = @erb.new("<%= foo %>")
assert_equal("1", erb.result_with_hash(foo: "1"))

View File

@ -92,6 +92,13 @@ class TestERBEncoding < Test::Unit::TestCase
assert_equal Encoding::EUC_KR, erb.result.encoding
end
def test_ignore_magic_comment_after_code
[nil, '%'].each do |trim_mode|
erb = ERB.new("<%# hello %><%= 1 %><%# coding: euc-jp %>", trim_mode: trim_mode)
assert_equal Encoding::UTF_8, erb.encoding
end
end
module M; end
def test_method_with_encoding
obj = Object.new