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 an incorrect auto-correct for Style/RedundantBegin #9777

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 @@
* [#9777](https://github.com/rubocop/rubocop/pull/9777): Fix an incorrect auto-correct for `Style/RedundantBegin` when using multi-line `if` in `begin` block. ([@koic][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/redundant_begin.rb
Expand Up @@ -110,7 +110,7 @@ def replace_begin_with_statement(corrector, offense_range, node)
first_child = node.children.first

source = first_child.source
source = "(#{source})" if first_child.if_type?
source = "(#{source})" if first_child.if_type? && first_child.modifier_form?

corrector.replace(offense_range, source)
corrector.remove(range_between(offense_range.end_pos, first_child.source_range.end_pos))
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cli/autocorrect_spec.rb
Expand Up @@ -553,6 +553,25 @@ def verify_section
expect(File.read('example.rb')).to eq(corrected)
end

it 'corrects `Style/RedundantBegin` with `Style/MultilineMemoization`' do
source = <<~RUBY
@memo ||= begin
if condition
do_something
end
end
RUBY
create_file('example.rb', source)
expect(cli.run(['-a', '--only', 'Style/RedundantBegin,Style/MultilineMemoization'])).to eq(0)
corrected = <<~RUBY
@memo ||= if condition
do_something
end
#{trailing_whitespace * 10}
RUBY
expect(File.read('example.rb')).to eq(corrected)
end

it 'corrects LineEndConcatenation offenses leaving the ' \
'RedundantInterpolation offense unchanged' do
# If we change string concatenation from plus to backslash, the string
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/style/redundant_begin_spec.rb
Expand Up @@ -248,6 +248,23 @@ def method
RUBY
end

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

expect_correction(<<~RUBY)
var ||= if condition
foo
end\n
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