diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f7b6a7dbd3..4f11ffba641 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ * [#8527](https://github.com/rubocop-hq/rubocop/pull/8527): Prevent an incorrect auto-correction for `Style/CaseEquality` cop when comparing with `===` against a regular expression receiver. ([@koic][]) * [#8524](https://github.com/rubocop-hq/rubocop/issues/8524): Fix `Layout/EmptyLinesAroundClassBody` and `Layout/EmptyLinesAroundModuleBody` to correctly handle an access modifier as a first child. ([@dsavochkin][]) * [#8518](https://github.com/rubocop-hq/rubocop/issues/8518): Fix `Lint/ConstantResolution` cop reporting offense for `module` and `class` definitions. ([@tejasbubane][]) +* [#8158](https://github.com/rubocop-hq/rubocop/issues/8158): Fix `Style/MultilineWhenThen` cop to correctly handle cases with multiline body. ([@dsavochkin][]) ### Changes diff --git a/lib/rubocop/cop/style/multiline_when_then.rb b/lib/rubocop/cop/style/multiline_when_then.rb index 6461fc38973..a30e45ae125 100644 --- a/lib/rubocop/cop/style/multiline_when_then.rb +++ b/lib/rubocop/cop/style/multiline_when_then.rb @@ -44,7 +44,7 @@ def on_when(node) # 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 + # For arrays and hashes there's no offense return if accept_node_type?(node.body) range = node.loc.begin @@ -64,7 +64,7 @@ def require_then?(when_node) end def accept_node_type?(node) - node&.begin_type? || node&.array_type? || node&.hash_type? + node&.array_type? || node&.hash_type? end end end diff --git a/spec/rubocop/cop/style/multiline_when_then_spec.rb b/spec/rubocop/cop/style/multiline_when_then_spec.rb index cf83ed670f9..231822601a1 100644 --- a/spec/rubocop/cop/style/multiline_when_then_spec.rb +++ b/spec/rubocop/cop/style/multiline_when_then_spec.rb @@ -18,7 +18,7 @@ RUBY end - it 'registers an offense for multiline when statement with then' do + it 'registers an offense for multiline (one line in a body) when statement with then' do expect_offense(<<~RUBY) case foo when bar then @@ -35,6 +35,25 @@ RUBY end + it 'registers an offense for multiline (two lines in a body) when statement with then' do + expect_offense(<<~RUBY) + case foo + when bar then + ^^^^ Do not use `then` for multiline `when` statement. + do_something1 + do_something2 + end + RUBY + + expect_correction(<<~RUBY) + case foo + when bar + do_something1 + do_something2 + end + RUBY + end + it "doesn't register an offense for singleline when statement with then" do expect_no_offenses(<<~RUBY) case foo