Skip to content

Commit

Permalink
[rubocop#116] Fix an incorrect autocorrect for Rails/Prensence
Browse files Browse the repository at this point in the history
Fixes rubocop#116 and adds regression test for rubocop#115.

This PR fixes an incorrect autocorrect for `Rails/Presence` when
`else` branch of ternary operator is not nil.

The following is a reproduction procedure.

```ruby
# example.rb
a.blank? ? 1 : a
```

```console
% bundle exec rubocop --only Rails/Presence -a
Inspecting 1 file
C

Offenses:

example.rb:1:1: C: [Corrected] Rails/Presence: Use a.presence instead of
a.blank? ? 1 : a.
a.blank? ? 1 : a
^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected
```

```diff
-a.blank? ? 1 : a
+a.presence
```

This PR is auto-corrected to `a.presence || 1`.
  • Loading branch information
koic committed Aug 27, 2019
1 parent 5aa0e98 commit 4e875be
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#116](https://github.com/rubocop-hq/rubocop-rails/issues/116): Fix an incorrect autocorrect for `Rails/Presence` when `else` branch of ternary operator is not nil. ([@koic][])

## 2.3.1 (2019-08-26)

### Bug fixes
Expand Down
4 changes: 3 additions & 1 deletion lib/rubocop/cop/rails/presence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,10 @@ def message(node, receiver, other)
def replacement(receiver, other)
or_source = if other&.send_type?
build_source_for_or_method(other)
else
elsif other.nil? || other.nil_type?
''
else
" || #{other.source}"
end

"#{receiver.source}.presence" + or_source
Expand Down
2 changes: 2 additions & 0 deletions spec/rubocop/cop/rails/presence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
it_behaves_like 'offense', '!a.present? ? b : a', 'a.presence || b', 1, 1
it_behaves_like 'offense', 'a.blank? ? b : a', 'a.presence || b', 1, 1
it_behaves_like 'offense', '!a.blank? ? a : b', 'a.presence || b', 1, 1
it_behaves_like 'offense', 'a.present? ? a : 1', 'a.presence || 1', 1, 1
it_behaves_like 'offense', 'a.blank? ? 1 : a', 'a.presence || 1', 1, 1

it_behaves_like 'offense',
'a(:bar).map(&:baz).present? ? a(:bar).map(&:baz) : nil',
Expand Down

0 comments on commit 4e875be

Please sign in to comment.