Skip to content

Commit

Permalink
[Fix rubocop#10926] Make Style/SafeNavigation aware of a redundant …
Browse files Browse the repository at this point in the history
…nil check

Fixes rubocop#10926.

This PR makes `Style/SafeNavigation` aware of a redundant nil check.

IMHO, the context of this patch is a minimal update.
OTOH, a new cop like `Style/RedundantNilCheck` cop may be implemented
if it is not suitable for this `Style/SafeNavigation` cop.
(But I'm not sure if it's the best.)
  • Loading branch information
koic committed Aug 17, 2022
1 parent 5d35825 commit c9c96e3
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
@@ -0,0 +1 @@
* [#10926](https://github.com/rubocop/rubocop/issues/10926): Make `Style/SafeNavigation` aware of a redundant nil check. ([@koic][])
4 changes: 2 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)
return if unsafe_method_used?(method_chain, method) && !method.safe_navigation?
return if method_chain.method?(:empty?)

add_offense(node) { |corrector| autocorrect(corrector, node) }
Expand All @@ -141,7 +141,7 @@ def autocorrect(corrector, node)

corrector.remove(begin_range(node, body))
corrector.remove(end_range(node, body))
corrector.insert_before(method_call.loc.dot, '&')
corrector.insert_before(method_call.loc.dot, '&') unless method_call.safe_navigation?
handle_comments(corrector, node, method_call)

add_safe_nav_to_all_methods_in_chain(corrector, method_call, body)
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/safe_navigation_spec.rb
Expand Up @@ -205,6 +205,17 @@
RUBY
end

it 'registers an offense when safe guard check and safe navigation method call are connected with `&&` condition' do
expect_offense(<<~RUBY, variable: variable)
%{variable} && %{variable}&.do_something
^{variable}^^^^^{variable}^^^^^^^^^^^^^^ Use safe navigation (`&.`) instead of checking if an object exists before calling the method.
RUBY

expect_correction(<<~RUBY)
#{variable}&.do_something
RUBY
end

it 'registers an offense for a method call on an accessor ' \
'safeguarded by a check for the accessed variable' do
expect_offense(<<~RUBY, variable: variable)
Expand Down

0 comments on commit c9c96e3

Please sign in to comment.