Skip to content

Commit

Permalink
Merge pull request rubocop#11863 from koic/fix_an_incorrect_autocorre…
Browse files Browse the repository at this point in the history
…ct_for_style_guard_clause

[Fix rubocop#11862] Fix an incorrect autocorrect for `Style/GuardClause`
  • Loading branch information
koic committed May 9, 2023
2 parents c567e1d + 91fc1be commit b8005a4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
@@ -0,0 +1 @@
* [#11862](https://github.com/rubocop/rubocop/issues/11862): Fix an incorrect autocorrect for `Style/GuardClause` when using `raise` in `else` branch in a one-liner with `then`. ([@koic][])
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/guard_clause.rb
Expand Up @@ -187,6 +187,8 @@ def autocorrect(corrector, node, condition, replacement, guard)
if_branch = node.if_branch
else_branch = node.else_branch

corrector.replace(node.loc.begin, "\n") if node.loc.begin&.is?('then')

if if_branch&.send_type? && heredoc?(if_branch.last_argument)
autocorrect_heredoc_argument(corrector, node, if_branch, else_branch, guard)
elsif else_branch&.send_type? && heredoc?(else_branch.last_argument)
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/guard_clause_spec.rb
Expand Up @@ -165,6 +165,18 @@ def func
expect_no_corrections
end

it 'registers an offense when using `raise` in `else` branch in a one-liner with `then`' do
expect_offense(<<~RUBY)
if something then work else raise('message') end
^^ Use a guard clause (`raise('message') unless something`) instead of wrapping the code inside a conditional expression.
RUBY

expect_correction(<<~RUBY)
raise('message') unless something#{trailing_whitespace}
work#{trailing_whitespace * 3}
RUBY
end

it 'registers an offense when using `and return` in `then` branch' do
expect_offense(<<~RUBY)
def func
Expand Down

0 comments on commit b8005a4

Please sign in to comment.