-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rails_belongs_to_optional.rb
57 lines (49 loc) · 1.46 KB
/
rails_belongs_to_optional.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
# frozen_string_literal: true
module RuboCop
module Cop
module Sevencop
# Force `belongs_to` with `optional: true` option.
#
# @example
#
# # bad
# belongs_to :group
#
# # good
# belongs_to :group, optional: true
#
# # good
# belongs_to :group, optional: false
#
# # good (We cannot identify offenses in this case.)
# belongs_to :group, options
#
class RailsBelongsToOptional < Base
extend AutoCorrector
MSG = 'Specify :optional option.'
RESTRICT_ON_SEND = %i[
belongs_to
].freeze
# @!method without_options?(node)
def_node_matcher :without_options?, <<~PATTERN
(send _ _ _ (block ...)?)
PATTERN
# @!method with_hash_options?(node)
def_node_matcher :with_hash_options?, <<~PATTERN
(send _ _ _ (block ...)? (hash ...))
PATTERN
# @!method with_optional?(node)
def_node_matcher :with_optional?, <<~PATTERN
(send _ _ _ (block ...)? (hash <(pair (sym :optional) _) ...>))
PATTERN
# @param [RuboCop::AST::SendNode] node
def on_send(node)
return unless without_options?(node) || (with_hash_options?(node) && !with_optional?(node))
add_offense(node) do |corrector|
corrector.insert_after(node.last_argument, ', optional: true')
end
end
end
end
end
end