Skip to content

Commit 9d17fc6

Browse files
authored
Engine: Fix ERB expression compilation when code contains a heredoc (#1206)
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. This is a sibling commit to the one introduced in marcoroth/reactionview#78
1 parent 3dbbbdd commit 9d17fc6

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
@@ -214,13 +214,17 @@ def add_expression(indicator, code)
214214

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

221223
def add_expression_result_escaped(code)
222224
with_buffer {
223-
@src << " << " << @escapefunc << "((" << code << comment_aware_newline(code) << "))"
225+
@src << " << " << @escapefunc << "((" << code
226+
@src << "\n" if heredoc?(code)
227+
@src << comment_aware_newline(code) << "))"
224228
}
225229
end
226230

@@ -248,6 +252,10 @@ def comment_aware_newline(code)
248252
code.include?("#") ? "\n" : ""
249253
end
250254

255+
def heredoc?(code)
256+
code.match?(/<<[~-]?\s*['"`]?\w/)
257+
end
258+
251259
def add_postamble(postamble)
252260
terminate_expression
253261
@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)