Skip to content

Commit

Permalink
[Fix #9681] Fix an incorrect auto-correct for Style/RedundantBegin
Browse files Browse the repository at this point in the history
Fixes #9681.

This PR fixes an incorrect auto-correct for `Style/RedundantBegin`
when using modifier `if` single statement in `begin` block.
  • Loading branch information
koic authored and bbatsov committed Apr 8, 2021
1 parent bcbd218 commit 1e55b1a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
@@ -0,0 +1 @@
* [#9681](https://github.com/rubocop/rubocop/issues/9681): Fix an incorrect auto-correct for `Style/RedundantBegin` when using modifier `if` single statement in `begin` block. ([@koic][])
5 changes: 4 additions & 1 deletion lib/rubocop/cop/style/redundant_begin.rb
Expand Up @@ -109,7 +109,10 @@ def register_offense(node)
def replace_begin_with_statement(corrector, offense_range, node)
first_child = node.children.first

corrector.replace(offense_range, first_child.source)
source = first_child.source
source = "(#{source})" if first_child.if_type?

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

restore_removed_comments(corrector, offense_range, node, first_child)
Expand Down
14 changes: 14 additions & 0 deletions spec/rubocop/cop/style/redundant_begin_spec.rb
Expand Up @@ -234,6 +234,20 @@ def method
RUBY
end

it 'registers and corrects an offense when using modifier `if` single statement in `begin` block' do
expect_offense(<<~RUBY)
var ||= begin
^^^^^ Redundant `begin` block detected.
foo if condition
end
RUBY

expect_correction(<<~RUBY)
var ||= (foo if condition)
RUBY
end

it 'does not register an offense when using `begin` with multiple statement for or assignment' do
expect_no_offenses(<<~RUBY)
var ||= begin
Expand Down

0 comments on commit 1e55b1a

Please sign in to comment.