diff --git a/changelog/fix_incorrect_autocorrect_for_style_eval_with_location.md b/changelog/fix_incorrect_autocorrect_for_style_eval_with_location.md new file mode 100644 index 00000000000..01afda5966f --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_style_eval_with_location.md @@ -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][]) diff --git a/lib/rubocop/cop/style/eval_with_location.rb b/lib/rubocop/cop/style/eval_with_location.rb index 2ccbd5d3ff7..3d91bde864f 100644 --- a/lib/rubocop/cop/style/eval_with_location.rb +++ b/lib/rubocop/cop/style/eval_with_location.rb @@ -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 diff --git a/spec/rubocop/cop/style/eval_with_location_spec.rb b/spec/rubocop/cop/style/eval_with_location_spec.rb index 72194c16a64..d797351b23a 100644 --- a/spec/rubocop/cop/style/eval_with_location_spec.rb +++ b/spec/rubocop/cop/style/eval_with_location_spec.rb @@ -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__