Skip to content

Commit 8097a1b

Browse files
Fix ERB expression compilation when code contains a heredoc
When an ERB output tag contains a heredoc (e.g. `<%= method_call <<~GRAPHQL, variables %>`), the closing parenthesis in the compiled Ruby must appear on its own line after the heredoc terminator. Without this, the compiled Ruby is syntactically invalid. Amp-Thread-ID: https://ampcode.com/threads/T-019c738c-52b4-772e-ab48-9bfb6b31e8f0 Co-authored-by: Amp <amp@ampcode.com>
1 parent 6ed505f commit 8097a1b

4 files changed

Lines changed: 37 additions & 2 deletions

File tree

lib/herb/engine.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,13 +213,17 @@ def add_expression(indicator, code)
213213

214214
def add_expression_result(code)
215215
with_buffer {
216-
@src << " << (" << code << comment_aware_newline(code) << ").to_s"
216+
@src << " << (" << code
217+
@src << "\n" if heredoc?(code)
218+
@src << comment_aware_newline(code) << ").to_s"
217219
}
218220
end
219221

220222
def add_expression_result_escaped(code)
221223
with_buffer {
222-
@src << " << " << @escapefunc << "((" << code << comment_aware_newline(code) << "))"
224+
@src << " << " << @escapefunc << "((" << code
225+
@src << "\n" if heredoc?(code)
226+
@src << comment_aware_newline(code) << "))"
223227
}
224228
end
225229

@@ -247,6 +251,10 @@ def comment_aware_newline(code)
247251
code.include?("#") ? "\n" : ""
248252
end
249253

254+
def heredoc?(code)
255+
code.match?(/<<[~-]?\s*['"`]?\w/)
256+
end
257+
250258
def add_postamble(postamble)
251259
terminate_expression
252260
@src << postamble

sig/herb/engine.rbs

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/engine/engine_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,5 +164,18 @@ class EngineTest < Minitest::Spec
164164

165165
assert_compiled_snapshot(template, escape: false)
166166
end
167+
168+
test "heredoc with trailing arguments compiles to valid Ruby" do
169+
template = <<~ERB
170+
<%= method_call <<~GRAPHQL, variables
171+
query {
172+
field
173+
}
174+
GRAPHQL
175+
%>
176+
ERB
177+
178+
assert_compiled_snapshot(template)
179+
end
167180
end
168181
end

test/snapshots/engine/engine_test/test_0018_heredoc_with_trailing_arguments_compiles_to_valid_Ruby_46fb4e6ec5bd55cc1041f3f88ad9508c.txt

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)