Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Style/RedundantBegin removing comments on assignment statement correction #9639

Merged
merged 1 commit into from Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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