/
unneeded_condition.rb
112 lines (95 loc) · 2.67 KB
/
unneeded_condition.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for unnecessary conditional expressions.
#
# @example
# # bad
# a = b ? b : c
#
# # good
# a = b || c
#
# @example
# # bad
# if b
# b
# else
# c
# end
#
# # good
# b || c
#
# # good
# if b
# b
# elsif cond
# c
# end
#
class UnneededCondition < Cop
include RangeHelp
MSG = 'Use double pipes `||` instead.'.freeze
UNNEEDED_CONDITION = 'This condition is not needed.'.freeze
def on_if(node)
return if node.elsif_conditional?
return unless offense?(node)
add_offense(node, location: range_of_offense(node))
end
def autocorrect(node)
lambda do |corrector|
if node.ternary?
corrector.replace(range_of_offense(node), '||')
elsif node.modifier_form? || !node.else_branch
corrector.replace(node.source_range, node.if_branch.source)
else
corrected = make_ternary_form(node)
corrector.replace(node.source_range, corrected)
end
end
end
private
def message(node)
if node.modifier_form? || !node.else_branch
UNNEEDED_CONDITION
else
MSG
end
end
def range_of_offense(node)
return :expression unless node.ternary?
range_between(node.loc.question.begin_pos, node.loc.colon.end_pos)
end
def offense?(node)
condition, if_branch, else_branch = *node
return false if use_if_branch?(else_branch)
condition == if_branch && !node.elsif? && (
node.ternary? ||
!else_branch.instance_of?(AST::Node) ||
else_branch.single_line?
)
end
def use_if_branch?(else_branch)
else_branch && else_branch.if_type?
end
def else_source(else_branch)
wrap_else =
else_branch.basic_conditional? && else_branch.modifier_form?
wrap_else ? "(#{else_branch.source})" : else_branch.source
end
def make_ternary_form(node)
_condition, if_branch, else_branch = *node
ternary_form = [if_branch.source,
else_source(else_branch)].join(' || ')
if node.parent && node.parent.send_type?
"(#{ternary_form})"
else
ternary_form
end
end
end
end
end
end