forked from rubocop/rubocop
/
in_pattern_then.rb
56 lines (46 loc) · 1.48 KB
/
in_pattern_then.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for `in;` uses in `case` expressions.
#
# @example
# # bad
# case expression
# in pattern_a; foo
# in pattern_b; bar
# end
#
# # good
# case expression
# in pattern_a then foo
# in pattern_b then bar
# end
#
class InPatternThen < Base
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.7
MSG = 'Do not use `in %<pattern>s;`. Use `in %<pattern>s then` instead.'
def on_in_pattern(node)
return if node.multiline? || node.then? || !node.body
pattern = node.pattern
pattern_source = if pattern.match_alt_type?
alternative_pattern_source(pattern)
else
pattern.source
end
add_offense(node.loc.begin, message: format(MSG, pattern: pattern_source)) do |corrector|
corrector.replace(node.loc.begin, ' then')
end
end
private
def alternative_pattern_source(pattern)
return pattern.children.map(&:source) unless pattern.children.first.match_alt_type?
pattern_sources = alternative_pattern_source(pattern.children.first)
(pattern_sources << pattern.children[1].source).join(' | ')
end
end
end
end
end