-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
consistent_parentheses_style.rb
111 lines (97 loc) · 2.98 KB
/
consistent_parentheses_style.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
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
module FactoryBot
# Use a consistent style for parentheses in factory bot calls.
#
# @example
#
# # bad
# create :user
# build(:user)
# create(:login)
# create :login
#
# @example `EnforcedStyle: require_parentheses` (default)
#
# # good
# create(:user)
# create(:user)
# create(:login)
# build(:login)
#
# @example `EnforcedStyle: omit_parentheses`
#
# # good
# create :user
# build :user
# create :login
# create :login
#
# # also good
# # when method name and first argument are not on same line
# create(
# :user
# )
# build(
# :user,
# name: 'foo'
# )
#
class ConsistentParenthesesStyle < Base
extend AutoCorrector
include ConfigurableEnforcedStyle
include RuboCop::RSpec::FactoryBot::Language
include RuboCop::Cop::Util
def self.autocorrect_incompatible_with
[Style::MethodCallWithArgsParentheses]
end
MSG_REQUIRE_PARENS = 'Prefer method call with parentheses'
MSG_OMIT_PARENS = 'Prefer method call without parentheses'
FACTORY_CALLS = RuboCop::RSpec::FactoryBot::Language::METHODS
# @!method factory_call(node)
def_node_matcher :factory_call, <<-PATTERN
(send
{#factory_bot? nil?} %FACTORY_CALLS
{sym str send lvar} _*
)
PATTERN
def on_send(node)
return if nested_call?(node) # prevent from nested matching
factory_call(node) do
if node.parenthesized?
process_with_parentheses(node)
else
process_without_parentheses(node)
end
end
end
def process_with_parentheses(node)
return unless style == :omit_parentheses
return unless same_line?(node, node.first_argument)
add_offense(node.loc.selector,
message: MSG_OMIT_PARENS) do |corrector|
remove_parentheses(corrector, node)
end
end
def process_without_parentheses(node)
return unless style == :require_parentheses
add_offense(node.loc.selector,
message: MSG_REQUIRE_PARENS) do |corrector|
add_parentheses(node, corrector)
end
end
def nested_call?(node)
node.parent&.send_type?
end
private
def remove_parentheses(corrector, node)
corrector.replace(node.location.begin, ' ')
corrector.remove(node.location.end)
end
end
end
end
end
end