Skip to content

Commit

Permalink
Merge pull request rubocop#7444 from koic/fix_incorrect_autocorrect_f…
Browse files Browse the repository at this point in the history
…or_style_safe_navigation

[Fix rubocop#7442] Fix an incorrect autocorrect for `Style/SafeNavigation`
  • Loading branch information
koic committed Oct 21, 2019
2 parents e436938 + eee7416 commit 777eeae
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
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][])

### Changes

Expand Down
13 changes: 6 additions & 7 deletions lib/rubocop/cop/style/safe_navigation.rb
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
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 777eeae

Please sign in to comment.