Skip to content

Commit

Permalink
[Fix #7635] Fix a false positive for Style/MultilineWhenThen
Browse files Browse the repository at this point in the history
Fixes #7635

This PR fixes a false positive for `Style/MultilineWhenThen`
when `then` required for a body of `when` is used.
  • Loading branch information
koic authored and bbatsov committed Apr 20, 2020
1 parent 5460e10 commit 1de14f6
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,7 @@
* [#7882](https://github.com/rubocop-hq/rubocop/pull/7882): Fix `Style/CaseEquality` when `AllowOnConstant` is `true` and the method receiver is implicit. ([@rafaelfranca][])
* [#7790](https://github.com/rubocop-hq/rubocop/issues/7790): Fix `--parallel` and `--ignore-parent-exclusion` combination. ([@jonas054][])
* [#7881](https://github.com/rubocop-hq/rubocop/issues/7881): Fix `--parallel` and `--force-default-config` combination. ([@jonas054][])
* [#7635](https://github.com/rubocop-hq/rubocop/issues/7635): Fix a false positive for `Style/MultilineWhenThen` when `then` required for a body of `when` is used. ([@koic][])

### Changes

Expand Down
17 changes: 16 additions & 1 deletion lib/rubocop/cop/style/multiline_when_then.rb
Expand Up @@ -22,6 +22,12 @@ module Style
# when bar then do_something
# end
#
# # good
# case foo
# when bar then do_something(arg1,
# arg2)
# end
#
class MultilineWhenThen < Cop
include RangeHelp

Expand All @@ -32,7 +38,10 @@ def on_when(node)
return unless node.then?

# Single line usage of `then` is not an offense
return if !node.children.last.nil? && !node.multiline? && node.then?
return if !node.children.last.nil? && !node.multiline?

# Requires `then` for write `when` and its body on the same line.
return if require_then?(node)

# With more than one statements after then, there's not offense
return if accept_node_type?(node.body)
Expand All @@ -50,6 +59,12 @@ def autocorrect(node)
end
end

def require_then?(when_node)
return false unless when_node.body

when_node.loc.line == when_node.body.loc.line
end

def accept_node_type?(node)
node&.begin_type? || node&.array_type? || node&.hash_type?
end
Expand Down
6 changes: 6 additions & 0 deletions manual/cops_style.md
Expand Up @@ -4206,6 +4206,12 @@ end
case foo
when bar then do_something
end

# good
case foo
when bar then do_something(arg1,
arg2)
end
```

### References
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/style/multiline_when_then_spec.rb
Expand Up @@ -30,6 +30,16 @@
RUBY
end

it "doesn't register an offense when `then` required for a body of `when` " \
'is used' do
expect_no_offenses(<<~RUBY)
case cond
when foo then do_something(arg1,
arg2)
end
RUBY
end

it "doesn't register an offense for multiline when statement
with then followed by other lines" do
expect_no_offenses(<<~RUBY)
Expand Down

0 comments on commit 1de14f6

Please sign in to comment.