Skip to content

Commit

Permalink
Fix Style/SafeNavigation for negated method call with a safe naviga…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
fatkodima committed Aug 21, 2022
1 parent dc09aae commit 1c0e98d
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 1c0e98d

Please sign in to comment.