Skip to content

Commit

Permalink
Scan forward until text tokens match
Browse files Browse the repository at this point in the history
Text tokens may be conditionally appended to the output buffer.  For
example if we have a template like this:

```erb
<h1>Oh no!</h1>
This template has a runtime error
<b>
  <% if true %>
    <%= method_that_does_not_exist %>
  <% end %>
</b>
Yikes!
```

In the above case, a string literal (`"    "`) will be conditionally
appended to the output buffer with some code like below:

```ruby
@output_buffer.safe_append='    '.freeze
```

This commit teaches text tokens (string literals) to scan forward in the
compiled template until it finds the literal, thereby skipping the code
generated for appending to the output buffer.

Related to:

* Bug: #48173
* PR: #48184
  • Loading branch information
tenderlove committed May 24, 2023
1 parent 61accb7 commit 5e35463
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
12 changes: 10 additions & 2 deletions actionview/lib/action_view/template/handlers/erb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,23 @@ def find_offset(compiled, source_tokens, error_column)
tok_name, str = *tok
case tok_name
when :TEXT
loop do
break if compiled.match?(str)
compiled.getch
end
raise LocationParsingError unless compiled.scan(str)
when :CODE
raise LocationParsingError, "We went too far" if compiled.pos > error_column
if compiled.pos > error_column
raise LocationParsingError, "We went too far"
end

if compiled.pos + str.bytesize >= error_column
offset = error_column - compiled.pos
return passed_tokens.map(&:last).join.bytesize + offset
else
raise LocationParsingError unless compiled.scan(str)
unless compiled.scan(str)
raise LocationParsingError, "Couldn't find code snippet"
end
end
when :OPEN
next_tok = source_tokens.first.last
Expand Down
4 changes: 2 additions & 2 deletions actionview/test/template/render_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def test_render_runtime_error
assert_equal 6, translated_spot[:first_column]
end

def test_render_location_map_failure
def test_render_location_conditional_append
ex = assert_raises(ActionView::Template::Error) {
@view.render(template: "test/unparseable_runtime_error")
}
Expand All @@ -232,7 +232,7 @@ def test_render_location_map_failure
translating_frame = ActionDispatch::ExceptionWrapper::SourceMapLocation.new(erb_btl, ex.template)
translated_spot = translating_frame.spot(ex.cause)

assert_not_nil translated_spot[:first_column]
assert_equal 8, translated_spot[:first_column]
end
end

Expand Down

0 comments on commit 5e35463

Please sign in to comment.