Skip to content

Commit

Permalink
Merge pull request #10946 from fatkodima/safe-navigation-negated
Browse files Browse the repository at this point in the history
Fix `Style/SafeNavigation` for negated method call with a safe navigation
  • Loading branch information
koic committed Aug 21, 2022
2 parents dc09aae + 1c0e98d commit 0048f70
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/rubocop/cop/style/safe_navigation.rb
Expand Up @@ -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) }
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions spec/rubocop/cop/style/safe_navigation_spec.rb
Expand Up @@ -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)
Expand Down

0 comments on commit 0048f70

Please sign in to comment.