Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Style/SafeNavigation for negated method call with a safe navigation #10946

Merged
merged 1 commit into from
Aug 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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