class RuboCop::Cop::Lint::SafeNavigationChain
x&.foo || bar
x&.foo&.bar
# good
@example
x&.foo[bar]
x&.foo + bar
x&.foo.bar
# bad
@example
This cop checks for the problem outlined above.
safe navigation operator after a safe navigation operator.
navigation operator, it raises NoMethodError. We should use a
nil. If you chain an ordinary method call after a safe
The safe navigation operator returns nil if the receiver is
def autocorrect(node)
def autocorrect(node) dot = node.loc.dot return unless dot lambda do |corrector| corrector.insert_before(dot, '&') end end
def nil_methods
def nil_methods nil.methods + ADDITIONAL_NIL_METHODS end
def on_send(node)
def on_send(node) bad_method?(node) do |method| return if nil_methods.include?(method) loc = node.loc.dot || :selector add_offense(node, loc) end end