Skip to content

Commit

Permalink
Merge pull request #9639 from marcotc/fix/RedundantBegin-remove-comments
Browse files Browse the repository at this point in the history
Fix `Style/RedundantBegin` removing comments on assignment statement correction
  • Loading branch information
koic committed Mar 29, 2021
2 parents 464c4df + 7288acd commit 8110f8f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
@@ -0,0 +1 @@
* [#9639](https://github.com/rubocop/rubocop/pull/9639): Fix `Style/RedundantBegin` removing comments on assignment statement correction. ([@marcotc][])
11 changes: 11 additions & 0 deletions lib/rubocop/cop/style/redundant_begin.rb
Expand Up @@ -114,6 +114,17 @@ def replace_begin_with_statement(corrector, offense_range, node)

corrector.replace(offense_range, first_child.source)
corrector.remove(range_between(offense_range.end_pos, first_child.source_range.end_pos))

restore_removed_comments(corrector, offense_range, node, first_child)
end

# Restore comments that occur between "begin" and "first_child".
# These comments will be moved to above the assignment line.
def restore_removed_comments(corrector, offense_range, node, first_child)
comments_range = range_between(offense_range.end_pos, first_child.source_range.begin_pos)
comments = comments_range.source

corrector.insert_before(node.parent, comments) unless comments.blank?
end

def empty_begin?(node)
Expand Down
11 changes: 9 additions & 2 deletions spec/rubocop/cop/style/redundant_begin_spec.rb
Expand Up @@ -197,14 +197,21 @@ def method

it 'registers and corrects an offense when using `begin` with single statement for or assignment' do
expect_offense(<<~RUBY)
var ||= begin
# outer comment
var ||= begin # inner comment 1
^^^^^ Redundant `begin` block detected.
# inner comment 2
foo
# inner comment 3
end
RUBY

expect_correction(<<~RUBY)
var ||= foo
# outer comment
# inner comment 1
# inner comment 2
var ||= foo
# inner comment 3
RUBY
end
Expand Down

0 comments on commit 8110f8f

Please sign in to comment.