diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c43236e2da..53bb2ab9253 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/style/multiline_when_then.rb b/lib/rubocop/cop/style/multiline_when_then.rb index 0ffc205d650..22596aec4ae 100644 --- a/lib/rubocop/cop/style/multiline_when_then.rb +++ b/lib/rubocop/cop/style/multiline_when_then.rb @@ -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 @@ -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) @@ -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 diff --git a/manual/cops_style.md b/manual/cops_style.md index 97bfe993395..dacc165e830 100644 --- a/manual/cops_style.md +++ b/manual/cops_style.md @@ -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 diff --git a/spec/rubocop/cop/style/multiline_when_then_spec.rb b/spec/rubocop/cop/style/multiline_when_then_spec.rb index f631ba6f425..f2144966141 100644 --- a/spec/rubocop/cop/style/multiline_when_then_spec.rb +++ b/spec/rubocop/cop/style/multiline_when_then_spec.rb @@ -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)