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 Lint/RedundantSafeNavigation when using to_s #11915

Merged
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
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