Skip to content

Commit

Permalink
Fix an incorrect autocorrect for Style/IfWithSemicolon
Browse files Browse the repository at this point in the history
This PR fixes the following incorrect autocorrect for `Style/IfWithSemicolon`
when using multiple expressions in the `else` body:

```console
$ cat example.rb
if cond; foo else bar'arg'; baz end

$ bundle exec rubocop --only Style/IfWithSemicolon -a
```

## Before

It results in an autocorrection of the syntax error:

```ruby
cond ? foo : bar'arg'; baz
```

## After

No syntax errors:

```ruby
if cond
 foo else bar'arg'; baz end
```
  • Loading branch information
koic authored and bbatsov committed Aug 28, 2024
1 parent 985c322 commit 4a338bb
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#13161](https://github.com/rubocop/rubocop/pull/13161): Fix incorrect autocorrect for `Style/IfWithSemicolon` when using multiple expressions in the `else` body. ([@koic][])
16 changes: 10 additions & 6 deletions lib/rubocop/cop/style/if_with_semicolon.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ def on_normal_if_unless(node)
message = message(node)

add_offense(node, message: message) do |corrector|
if node.if_branch&.begin_type?
corrector.replace(node.loc.begin, "\n")
else
corrector.replace(node, replacement(node))
end
autocorrect(corrector, node)
end
end

Expand All @@ -43,7 +39,7 @@ def on_normal_if_unless(node)
def message(node)
template = if node.if_branch&.begin_type?
MSG_NEWLINE
elsif node.else_branch&.if_type?
elsif node.else_branch&.if_type? || node.else_branch&.begin_type?
MSG_IF_ELSE
else
MSG_TERNARY
Expand All @@ -52,6 +48,14 @@ def message(node)
format(template, expr: node.condition.source)
end

def autocorrect(corrector, node)
if node.if_branch&.begin_type? || node.else_branch&.begin_type?
corrector.replace(node.loc.begin, "\n")
else
corrector.replace(node, replacement(node))
end
end

def replacement(node)
return correct_elsif(node) if node.else_branch&.if_type?

Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/if_with_semicolon_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,18 @@
RUBY
end

it 'registers an offense when using multiple expressions in the `else` branch' do
expect_offense(<<~RUBY)
if cond; foo else bar'arg'; baz end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use `if/else` instead.
RUBY

expect_correction(<<~RUBY)
if cond
foo else bar'arg'; baz end
RUBY
end

it 'can handle modifier conditionals' do
expect_no_offenses(<<~RUBY)
class Hash
Expand Down

0 comments on commit 4a338bb

Please sign in to comment.