diff --git a/lib/rubocop/cop/style/safe_navigation.rb b/lib/rubocop/cop/style/safe_navigation.rb index cb85fe58cb5..66369e92ffb 100644 --- a/lib/rubocop/cop/style/safe_navigation.rb +++ b/lib/rubocop/cop/style/safe_navigation.rb @@ -123,7 +123,7 @@ def check_node(node) return unless receiver == checked_variable return if use_var_only_in_unless_modifier?(node, checked_variable) return if chain_length(method_chain, method) > max_chain_length - return if unsafe_method_used?(method_chain, method) && !method.safe_navigation? + return if unsafe_method_used?(method_chain, method) return if method_chain.method?(:empty?) add_offense(node) { |corrector| autocorrect(corrector, node) } @@ -250,7 +250,9 @@ def unsafe_method_used?(method_chain, method) end def unsafe_method?(send_node) - negated?(send_node) || send_node.assignment? || !send_node.dot? + negated?(send_node) || + send_node.assignment? || + (!send_node.dot? && !send_node.safe_navigation?) end def negated?(send_node) diff --git a/spec/rubocop/cop/style/safe_navigation_spec.rb b/spec/rubocop/cop/style/safe_navigation_spec.rb index 3656f10a8a0..d2fcf75aaec 100644 --- a/spec/rubocop/cop/style/safe_navigation_spec.rb +++ b/spec/rubocop/cop/style/safe_navigation_spec.rb @@ -116,6 +116,10 @@ expect_no_offenses('foo.baz = bar if foo') end + it 'allows an object check before a negated method call with a safe navigation' do + expect_no_offenses('obj && !obj&.do_something') + end + it 'allows object checks in the condition of an elsif statement ' \ 'and a method call on that object in the body' do expect_no_offenses(<<~RUBY)