forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
require_parentheses.rb
66 lines (56 loc) · 1.78 KB
/
require_parentheses.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 Lint
# This cop checks for expressions where there is a call to a predicate
# method with at least one argument, where no parentheses are used around
# the parameter list, and a boolean operator, && or ||, is used in the
# last argument.
#
# The idea behind warning for these constructs is that the user might
# be under the impression that the return value from the method call is
# an operand of &&/||.
#
# @example
#
# # bad
#
# if day.is? :tuesday && month == :jan
# # ...
# end
#
# @example
#
# # good
#
# if day.is?(:tuesday) && month == :jan
# # ...
# end
class RequireParentheses < Cop
include RangeHelp
MSG = 'Use parentheses in the method call to avoid confusion about ' \
'precedence.'.freeze
def on_send(node)
return if !node.arguments? || node.parenthesized?
if node.first_argument.if_type? && node.first_argument.ternary?
check_ternary(node.first_argument, node)
elsif node.predicate_method?
check_predicate(node.last_argument, node)
end
end
alias on_csend on_send
private
def check_ternary(ternary, node)
return unless ternary.condition.operator_keyword?
range = range_between(node.source_range.begin_pos,
ternary.condition.source_range.end_pos)
add_offense(range, location: range)
end
def check_predicate(predicate, node)
return unless predicate.operator_keyword?
add_offense(node)
end
end
end
end
end