Skip to content

Commit

Permalink
Support autocorrection for Lint/SafeNavigationWithEmpty
Browse files Browse the repository at this point in the history
This PR supports autocorrection for `Lint/SafeNavigationWithEmpty`.
  • Loading branch information
koic committed Jun 29, 2020
1 parent a26b716 commit c2fe004
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 3 deletions.
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

0 comments on commit c2fe004

Please sign in to comment.