/
multiline_when_then.rb
74 lines (63 loc) · 1.77 KB
/
multiline_when_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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks uses of the `then` keyword
# in multi-line when statements.
#
# @example
# # bad
# case foo
# when bar then
# end
#
# # good
# case foo
# when bar
# end
#
# # good
# case foo
# when bar then do_something
# end
#
# # good
# case foo
# when bar then do_something(arg1,
# arg2)
# end
#
class MultilineWhenThen < Cop
include RangeHelp
MSG = 'Do not use `then` for multiline `when` statement.'
def on_when(node)
# Without `then`, there's no offense
return unless node.then?
# Single line usage of `then` is not an offense
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)
add_offense(node, location: :begin)
end
def autocorrect(node)
lambda do |corrector|
corrector.remove(
range_with_surrounding_space(
range: node.loc.begin, side: :left, newlines: false
)
)
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
end
end
end
end