Skip to content

Commit

Permalink
Fix Lint/RedundantSafeNavigation when using to_s
Browse files Browse the repository at this point in the history
  • Loading branch information
lucthev committed Jun 2, 2023
1 parent e216c9b commit d357b33
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 17 deletions.
1 change: 1 addition & 0 deletions changelog/fix_switch_back_the_docs_version.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11915](https://github.com/rubocop/rubocop/pull/11915): Fix a false positive for `Lint/RedundantSafeNavigation` when `&.` is used for `to_s`, `to_i`, `to_d`, and other coercion methods. ([@lucthev][])
4 changes: 2 additions & 2 deletions lib/rubocop/cop/lint/redundant_safe_navigation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ module Lint
# do_something if attrs&.not_nil_safe_method(:[])
#
class RedundantSafeNavigation < Base
include NilMethods
include AllowedMethods
include RangeHelp
extend AutoCorrector

Expand All @@ -63,7 +63,7 @@ class RedundantSafeNavigation < Base
PATTERN

def on_csend(node)
return unless check?(node) && nil_methods.include?(node.method_name)
return unless check?(node) && allowed_method?(node.method_name)
return if respond_to_nil_specific_method?(node)

range = range_between(node.loc.dot.begin_pos, node.source_range.end_pos)
Expand Down
23 changes: 8 additions & 15 deletions spec/rubocop/cop/lint/redundant_safe_navigation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,6 @@
RUBY
end

it 'registers an offense and corrects when `&.` is used for `to_d`' do
expect_offense(<<~RUBY)
if foo&.to_d
^^^^^^ Redundant safe navigation detected.
do_something_else
end
RUBY

expect_correction(<<~RUBY)
if foo.to_d
do_something_else
end
RUBY
end

it 'does not register an offense when using `&.` outside of conditions' do
expect_no_offenses(<<~RUBY)
foo&.respond_to?(:bar)
Expand All @@ -108,4 +93,12 @@
do_something if foo&.respond_to?(:to_a)
RUBY
end

it 'does not register an offense when `&.` is used with coercion methods' do
expect_no_offenses(<<~RUBY)
foo&.to_s || 'Default string'
foo&.to_i || 1
do_something if foo&.to_d
RUBY
end
end

0 comments on commit d357b33

Please # to comment.