Skip to content

Commit

Permalink
Fix an incorrect auto-correct for Style/EvalWithLocation
Browse files Browse the repository at this point in the history
Fixes standardrb/standard#275.

This PR fixes the following incorrect auto-correct for `Style/EvalWithLocation`
when using `#instance_eval` with a string argument in parentheses.

```console
% cat example.rb
instance_eval('@foo = foo')

% rubocop -A --only Style/EvalWithLocation
(snip)

Inspecting 1 file
C

Offenses:

example.rb:1:1: C: [Corrected] Style/EvalWithLocation: Pass __FILE__ and
__LINE__ to instance_eval.
instance_eval('@foo = foo')
^^^^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected
```

## Before

```console
% cat example.rb
instance_eval('@foo = foo'), __FILE__, __LINE__

% ruby -c example.rb
example.rb:1: syntax error, unexpected ',', expecting end-of-input
instance_eval('@foo = foo'), __FILE__, __LINE__
```

## After

```console
% cat example.rb
instance_eval('@foo = foo', __FILE__, __LINE__)

% ruby -c example.rb
Syntax OK
```
  • Loading branch information
koic committed Mar 18, 2021
1 parent 6746f15 commit 10aa0cc
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
@@ -0,0 +1 @@
* [#9616](https://github.com/rubocop/rubocop/pull/9616): Fix an incorrect auto-correct for `Style/EvalWithLocation` when using `#instance_eval` with a string argument in parentheses. ([@koic][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/eval_with_location.rb
Expand Up @@ -224,7 +224,7 @@ def add_offense_for_missing_location(node, code)

register_offense(node) do |corrector|
line_str = missing_line(node, code)
corrector.insert_after(node.loc.expression.end, ", __FILE__, #{line_str}")
corrector.insert_after(node.last_argument.source_range.end, ", __FILE__, #{line_str}")
end
end

Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/eval_with_location_spec.rb
Expand Up @@ -159,6 +159,17 @@
RUBY
end

it 'registers an offense when using `#instance_eval` with a string argument in parentheses' do
expect_offense(<<~RUBY)
instance_eval('@foo = foo')
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass `__FILE__` and `__LINE__` to `instance_eval`.
RUBY

expect_correction(<<~RUBY)
instance_eval('@foo = foo', __FILE__, __LINE__)
RUBY
end

it 'registers an offense when using `#class_eval` with an incorrect lineno' do
expect_offense(<<~RUBY)
C.class_eval <<-CODE, __FILE__, __LINE__
Expand Down

0 comments on commit 10aa0cc

Please sign in to comment.