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

Support autocorrection for Lint/SafeNavigationWithEmpty #8172

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.md
Expand Up @@ -8,6 +8,7 @@
* [#8213](https://github.com/rubocop-hq/rubocop/pull/8213): Permit to specify TargetRubyVersion 2.8 (experimental). ([@koic][])
* [#8164](https://github.com/rubocop-hq/rubocop/pull/8164): Support auto-correction for `Lint/InterpolationCheck`. ([@koic][])
* [#8223](https://github.com/rubocop-hq/rubocop/pull/8223): Support auto-correction for `Style/IfUnlessModifierOfIfUnless`. ([@koic][])
* [#8172](https://github.com/rubocop-hq/rubocop/pull/8172): Support auto-correction for `Lint/SafeNavigationWithEmpty`. ([@koic][])

### Bug fixes

Expand Down
1 change: 1 addition & 0 deletions config/default.yml
Expand Up @@ -1738,6 +1738,7 @@ Lint/SafeNavigationWithEmpty:
Description: 'Avoid `foo&.empty?` in conditionals.'
Enabled: true
VersionAdded: '0.62'
VersionChanged: '0.87'

Lint/ScriptPermission:
Description: 'Grant script file execute permission.'
Expand Down
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/cops_lint.adoc
Expand Up @@ -2826,9 +2826,9 @@ foo&.bar && (foobar.baz || foo&.baz)

| Enabled
| Yes
| No
| Yes
| 0.62
| -
| 0.87
|===

This cop checks to make sure safe navigation isn't used with `empty?` in
Expand Down
8 changes: 8 additions & 0 deletions lib/rubocop/cop/lint/safe_navigation_with_empty.rb
Expand Up @@ -32,6 +32,14 @@ def on_if(node)

add_offense(node.condition)
end

def autocorrect(node)
lambda do |corrector|
receiver = node.receiver.source

corrector.replace(node, "#{receiver} && #{receiver}.#{node.method_name}")
end
end
end
end
end
Expand Down
6 changes: 5 additions & 1 deletion spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb
Expand Up @@ -4,11 +4,15 @@
subject(:cop) { described_class.new }

context 'in a conditional' do
it 'registers an offense on `&.empty?`' do
it 'registers an offense and corrects on `&.empty?`' do
expect_offense(<<~RUBY)
return unless foo&.empty?
^^^^^^^^^^^ Avoid calling `empty?` with the safe navigation operator in conditionals.
RUBY

expect_correction(<<~RUBY)
return unless foo && foo.empty?
RUBY
end

it 'does not register an offense on `.empty?`' do
Expand Down