Skip to content

Commit

Permalink
Merge pull request #12411 from koic/fix_incorrect_autocorrect_for_lin…
Browse files Browse the repository at this point in the history
…t_safe_navigation_chain

[Fix #12409] Fix an incorrect autocorrect for `Lint/SafeNavigationChain`
  • Loading branch information
koic committed Nov 25, 2023
2 parents 09cba51 + 45ca1eb commit be4a19a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12409](https://github.com/rubocop/rubocop/issues/12409): Fix an incorrect autocorrect for `Lint/SafeNavigationChain` when ordinary method chain exists after safe navigation leading dot method call. ([@koic][])
7 changes: 3 additions & 4 deletions lib/rubocop/cop/lint/safe_navigation_chain.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,9 @@ def on_send(node)
bad_method?(node) do |safe_nav, method|
return if nil_methods.include?(method) || PLUS_MINUS_METHODS.include?(node.method_name)

location =
Parser::Source::Range.new(node.source_range.source_buffer,
safe_nav.source_range.end_pos,
node.source_range.end_pos)
begin_range = node.loc.dot || safe_nav.source_range.end
location = begin_range.join(node.source_range.end)

add_offense(location) do |corrector|
autocorrect(corrector, offense_range: location, send_node: node)
end
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/lint/safe_navigation_chain_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,21 @@
RUBY
end

it 'registers an offense for ordinary method chain exists after safe navigation leading dot method call' do
expect_offense(<<~RUBY)
x&.foo
&.bar
.baz
^^^^ Do not chain ordinary method call after safe navigation operator.
RUBY

expect_correction(<<~RUBY)
x&.foo
&.bar
&.baz
RUBY
end

it 'registers an offense for ordinary method chain exists after ' \
'safe navigation method call with an argument' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit be4a19a

Please sign in to comment.