Skip to content

Commit

Permalink
[Fix #9233] Improve handling of comments in SoleNestedConditional aut…
Browse files Browse the repository at this point in the history
…ocorrection

Previously it would gather all comments up to the root node, bringing non-relevant comments to the if node.
  • Loading branch information
Darhazer committed Jan 6, 2021
1 parent 653df19 commit 8955250
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9233](https://github.com/rubocop-hq/rubocop/issues/9233): Fix `Style/SoleNestedConditional` copying non-relevant comments during auto-correction. ([@Darhazer][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/sole_nested_conditional.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def correct_for_basic_condition_style(corrector, node, if_branch, and_operator)
def correct_for_comment(corrector, node, if_branch)
return if config.for_cop('Style/IfUnlessModifier')['Enabled']

comments = processed_source.comments_before_line(if_branch.source_range.line)
comments = processed_source.ast_with_comments[if_branch]
comment_text = comments.map(&:text).join("\n") << "\n"

corrector.insert_before(node.loc.keyword, comment_text) unless comments.empty?
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/style/sole_nested_conditional_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,27 @@
end
RUBY
end

it 'registers an offense and corrects when there are outer and inline comments' do
expect_offense(<<~RUBY)
# Outer comment.
if foo
# Comment.
if bar # nested condition
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY

expect_correction(<<~RUBY)
# Outer comment.
# Comment.
if foo && bar # nested condition
do_something
end
RUBY
end
end

it 'registers an offense and corrects when using guard conditional with outer comment' do
Expand Down

0 comments on commit 8955250

Please sign in to comment.