Skip to content

Commit

Permalink
Tweak autocorrection for Style/RedundantBegin
Browse files Browse the repository at this point in the history
This PR tweaks autocorrection for `Style/RedundantBegin`
when using endless method definition with redundant `begin`.

```ruby
def foo = begin
  bar
end
```

## Before

```console
% bundle exec rubocop --only Style/RedundantBegin -a
(snip)

example.rb:1:11: C: [Corrected] Style/RedundantBegin: Redundant begin block detected.
def foo = begin
          ^^^^^

1 file inspected, 1 offense detected, 1 offense corrected
```

```ruby
def foo =
  bar
```

## After

```ruby
def foo =  bar
```

This would be more closer to a one-liner endless idiom.
  • Loading branch information
koic authored and bbatsov committed Sep 30, 2023
1 parent 5f17749 commit c9819f1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/rubocop/cop/style/redundant_begin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def register_offense(node)
if node.parent&.assignment?
replace_begin_with_statement(corrector, offense_range, node)
else
corrector.remove(offense_range)
remove_begin(corrector, offense_range, node)
end

if use_modifier_form_after_multiline_begin_block?(node)
Expand All @@ -136,6 +136,14 @@ def replace_begin_with_statement(corrector, offense_range, node)
restore_removed_comments(corrector, offense_range, node, first_child)
end

def remove_begin(corrector, offense_range, node)
if node.parent.respond_to?(:endless?) && node.parent.endless?
offense_range = range_with_surrounding_space(offense_range, newlines: true)
end

corrector.remove(offense_range)
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)
Expand Down
2 changes: 1 addition & 1 deletion spec/rubocop/cop/style/redundant_begin_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ def foo = begin
end
RUBY

expect_correction("def foo = \n bar\n\n")
expect_correction("def foo = bar\n\n")
end

it 'accepts when `begin` block has multiple statements' do
Expand Down

0 comments on commit c9819f1

Please sign in to comment.