class RuboCop::Cop::Lint::SafeNavigationChain

The safe navigation operator returns nil if the receiver is nil. If you chain an ordinary method call after a safe navigation operator, it raises NoMethodError. We should use a safe navigation operator after a safe navigation operator. This cop checks for the problem outlined above.

@example

# bad

x&.foo.bar
x&.foo + bar
x&.foo[bar]

@example

# good

x&.foo&.bar
x&.foo || bar

Constants

MSG

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/lint/safe_navigation_chain.rb, line 47
def autocorrect(node)
  dot = node.loc.dot

  return unless dot

  lambda do |corrector|
    corrector.insert_before(dot, '&')
  end
end
on_send(node) click to toggle source
# File lib/rubocop/cop/lint/safe_navigation_chain.rb, line 37
def on_send(node)
  bad_method?(node) do |method|
    return if nil_methods.include?(method)

    loc = node.loc.dot || :selector

    add_offense(node, location: loc)
  end
end

Private Instance Methods

nil_methods() click to toggle source
# File lib/rubocop/cop/lint/safe_navigation_chain.rb, line 59
def nil_methods
  nil.methods + whitelist
end
whitelist() click to toggle source
# File lib/rubocop/cop/lint/safe_navigation_chain.rb, line 63
def whitelist
  cop_config['Whitelist'].map(&:to_sym)
end