/
sole_nested_conditional.rb
66 lines (58 loc) · 1.64 KB
/
sole_nested_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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# If the branch of a conditional consists solely of a conditional node,
# its conditions can be combined with the conditions of the outer branch.
# This helps to keep the nesting level from getting too deep.
#
# @example
# # bad
# if condition_a
# if condition_b
# do_something
# end
# end
#
# # good
# if condition_a && condition_b
# do_something
# end
#
# @example AllowModifier: false (default)
# # bad
# if condition_a
# do_something if condition_b
# end
#
# @example AllowModifier: true
# # good
# if condition_a
# do_something if condition_b
# end
#
class SoleNestedConditional < Base
MSG = 'Consider merging nested conditions into '\
'outer `%<conditional_type>s` conditions.'
def on_if(node)
return if node.ternary? || node.else? || node.elsif?
branch = node.if_branch
return unless offending_branch?(branch)
message = format(MSG, conditional_type: node.keyword)
add_offense(branch.loc.keyword, message: message)
end
private
def offending_branch?(branch)
return false unless branch
branch.if_type? &&
!branch.else? &&
!branch.ternary? &&
!(branch.modifier_form? && allow_modifier?)
end
def allow_modifier?
cop_config['AllowModifier']
end
end
end
end
end