Class: RuboCop::Cop::Gusto::ConstantSafety

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

Overview

Flags safe navigation (&.) called on a constant, covering both class/module constants (Model&.find) and SCREAMING_CASE constants (CONST&.each).

A constant reference is never nil, an undefined constant raises NameError before the call is even attempted, so the safe navigation operator is always redundant. Use the plain . operator instead.

Examples:

# bad
Model&.find(id)
ENTITY_TYPES&.each { |type| type.to_s }
Foo::Bar&.call
::Foo&.call

# good
Model.find(id)
ENTITY_TYPES.each { |type| type.to_s }
Foo::Bar.call
::Foo.call

Constant Summary collapse

MSG =
"Do not use safe navigation (`&.`) on a constant; constants are never `nil`, so use `.` instead."

Instance Method Summary collapse

Instance Method Details

#on_csend(node) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/rubocop/cop/gusto/constant_safety.rb', line 31

def on_csend(node)
  return unless node.receiver.const_type?

  add_offense(node.loc.dot) do |corrector|
    corrector.replace(node.loc.dot, ".")
  end
end