Skip to content

Commit

Permalink
Refine offense message for Style/WhenThen
Browse files Browse the repository at this point in the history
This PR refines offense message for `Style/WhenThen`.
It uses actual value of `when` for offense message.
  • Loading branch information
koic authored and bbatsov committed May 27, 2021
1 parent 7551234 commit 8cbb5a2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
8 changes: 6 additions & 2 deletions lib/rubocop/cop/style/when_then.rb
Expand Up @@ -20,12 +20,16 @@ module Style
class WhenThen < Base
extend AutoCorrector

MSG = 'Do not use `when x;`. Use `when x then` instead.'
MSG = 'Do not use `when %<expression>s;`. Use `when %<expression>s then` instead.'

def on_when(node)
return if node.multiline? || node.then? || !node.body

add_offense(node.loc.begin) { |corrector| corrector.replace(node.loc.begin, ' then') }
message = format(MSG, expression: node.conditions.map(&:source).join(', '))

add_offense(node.loc.begin, message: message) do |corrector|
corrector.replace(node.loc.begin, ' then')
end
end
end
end
Expand Down
19 changes: 17 additions & 2 deletions spec/rubocop/cop/style/when_then_spec.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true

RSpec.describe RuboCop::Cop::Style::WhenThen, :config do
it 'registers an offense for when x;' do
it 'registers an offense for when b;' do
expect_offense(<<~RUBY)
case a
when b; c
^ Do not use `when x;`. Use `when x then` instead.
^ Do not use `when b;`. Use `when b then` instead.
end
RUBY

Expand All @@ -16,6 +16,21 @@
RUBY
end

it 'registers an offense for when b, c;' do
expect_offense(<<~RUBY)
case a
when b, c; d
^ Do not use `when b, c;`. Use `when b, c then` instead.
end
RUBY

expect_correction(<<~RUBY)
case a
when b, c then d
end
RUBY
end

it 'accepts ; separating statements in the body of when' do
expect_no_offenses(<<~RUBY)
case a
Expand Down

0 comments on commit 8cbb5a2

Please sign in to comment.