forked from rubocop/rubocop
/
redundant_conditional.rb
97 lines (79 loc) · 2.38 KB
/
redundant_conditional.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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for redundant returning of true/false in conditionals.
#
# @example
# # bad
# x == y ? true : false
#
# # bad
# if x == y
# true
# else
# false
# end
#
# # good
# x == y
#
# # bad
# x == y ? false : true
#
# # good
# x != y
class RedundantConditional < Base
include Alignment
extend AutoCorrector
operators = RuboCop::AST::Node::COMPARISON_OPERATORS.to_a
COMPARISON_OPERATOR_MATCHER = "{:#{operators.join(' :')}}"
MSG = 'This conditional expression can just be replaced ' \
'by `%<msg>s`.'
def on_if(node)
return unless offense?(node)
message = message(node)
add_offense(node, message: message) do |corrector|
corrector.replace(node, replacement_condition(node))
end
end
private
def message(node)
replacement = replacement_condition(node)
msg = node.elsif? ? "\n#{replacement}" : replacement
format(MSG, msg: msg)
end
def_node_matcher :redundant_condition?, <<~RUBY
(if (send _ #{COMPARISON_OPERATOR_MATCHER} _) true false)
RUBY
def_node_matcher :redundant_condition_inverted?, <<~RUBY
(if (send _ #{COMPARISON_OPERATOR_MATCHER} _) false true)
RUBY
def offense?(node)
return if node.modifier_form?
redundant_condition?(node) || redundant_condition_inverted?(node)
end
def replacement_condition(node)
condition = node.condition.source
expression = invert_expression?(node) ? "!(#{condition})" : condition
node.elsif? ? indented_else_node(expression, node) : expression
end
def invert_expression?(node)
(
(node.if? || node.elsif? || node.ternary?) &&
redundant_condition_inverted?(node)
) || (
node.unless? &&
redundant_condition?(node)
)
end
def indented_else_node(expression, node)
"else\n#{indentation(node)}#{expression}"
end
def configured_indentation_width
super || 2
end
end
end
end
end