Class: RuboCop::Cop::Sevencop::RailsBelongsToOptional

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/sevencop/rails_belongs_to_optional.rb

Overview

Force ‘belongs_to` with `optional: true` option.

Examples:


# 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

Constant Summary collapse

MSG =
'Specify :optional option.'
RESTRICT_ON_SEND =
%i[
  belongs_to
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object

Parameters:

  • node (RuboCop::AST::SendNode)


47
48
49
50
51
52
53
# File 'lib/rubocop/cop/sevencop/rails_belongs_to_optional.rb', line 47

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

#with_hash_options?(node) ⇒ Object



37
38
39
# File 'lib/rubocop/cop/sevencop/rails_belongs_to_optional.rb', line 37

def_node_matcher :with_hash_options?, <<~PATTERN
  (send _ _ _ (block ...)? (hash ...))
PATTERN

#with_optional?(node) ⇒ Object



42
43
44
# File 'lib/rubocop/cop/sevencop/rails_belongs_to_optional.rb', line 42

def_node_matcher :with_optional?, <<~PATTERN
  (send _ _ _ (block ...)? (hash <(pair (sym :optional) _) ...>))
PATTERN

#without_options?(node) ⇒ Object



32
33
34
# File 'lib/rubocop/cop/sevencop/rails_belongs_to_optional.rb', line 32

def_node_matcher :without_options?, <<~PATTERN
  (send _ _ _ (block ...)?)
PATTERN