From 1c0e98d74f19099a45ad93f357998276162ded99 Mon Sep 17 00:00:00 2001 From: fatkodima Date: Sun, 21 Aug 2022 15:16:43 +0300 Subject: [PATCH] Fix `Style/SafeNavigation` for negated method call with a safe navigation --- lib/rubocop/cop/style/safe_navigation.rb | 6 ++++-- spec/rubocop/cop/style/safe_navigation_spec.rb | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) 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)