Skip to content

Commit

Permalink
[Fix rubocop#7442] Fix an incorrect autocorrect for `Style/SafeNaviga…
Browse files Browse the repository at this point in the history
…tion`

Fixes rubocop#7442.

This PR fixes an incorrect autocorrect for `Style/SafeNavigation`
when an object check followed by a method call with a comment at EOL.
  • Loading branch information
koic committed Oct 21, 2019
1 parent d6ceaa3 commit eee7416
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* [#7439](https://github.com/rubocop-hq/rubocop/issues/7439): Make `Style/FormatStringToken` ignore percent escapes (`%%`). ([@buehmann][])
* [#7438](https://github.com/rubocop-hq/rubocop/issues/7438): Fix assignment edge-cases in `Layout/MultilineAssignmentLayout`. ([@gsamokovarov][])
* [#7449](https://github.com/rubocop-hq/rubocop/pull/7449): Make `Style/IfUnlessModifier` respect `rubocop:disable` comments for `Metrics/LineLength`. ([@jonas054][])
* [#7442](https://github.com/rubocop-hq/rubocop/issues/7442): Fix an incorrect autocorrect for `Style/SafeNavigation` when an object check followed by a method call with a comment at EOL. ([@koic][])

## 0.75.1 (2019-10-14)

Expand Down
13 changes: 6 additions & 7 deletions lib/rubocop/cop/style/safe_navigation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,19 +129,18 @@ def autocorrect(node)
private

def handle_comments(corrector, node, method_call)
return if processed_source.comments.empty?
comments = comments(node)
return if comments.empty?

corrector.insert_before(method_call.loc.expression,
"#{comments(node).join("\n")}\n")
"#{comments.map(&:text).join("\n")}\n")
end

def comments(node)
comments = processed_source.comments.select do |comment|
comment.loc.first_line >= node.loc.first_line &&
comment.loc.last_line <= node.loc.last_line
processed_source.comments.select do |comment|
comment.loc.first_line > node.loc.first_line &&
comment.loc.last_line < node.loc.last_line
end

comments.map(&:text)
end

def allowed_if_condition?(node)
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/style/safe_navigation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,15 @@
expect(new_source).to eq("#{variable}&.bar(baz)")
end

it 'corrects an object check followed by a method call ' \
'with a comment at EOL' do
source = "foo if #{variable} && #{variable}.bar # comment"

new_source = autocorrect_source(source)

expect(new_source).to eq("foo if #{variable}&.bar # comment")
end

it 'corrects a method call with a block safeguarded with a check ' \
'for the object' do
source = "#{variable}.bar { |e| e.qux } if #{variable}"
Expand Down

0 comments on commit eee7416

Please sign in to comment.