Skip to content

Commit 3a0998c

Browse files
committed
[Fix #116] Fix an incorrect autocorrect for Rails/Prensence
Fixes #116 and adds regression tests for #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 will auto-correct it to `a.presence || 1`.
1 parent 7766c50 commit 3a0998c

File tree

3 files changed

+6
-1
lines changed

3 files changed

+6
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
### Bug fixes
66

77
* [#118](https://github.com/rubocop-hq/rubocop-rails/issues/118): Fix an incorrect autocorrect for `Rails/Validation` when attributes are specified with array literal. ([@koic][])
8+
* [#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][])
89

910
## 2.3.1 (2019-08-26)
1011

lib/rubocop/cop/rails/presence.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,10 @@ def message(node, receiver, other)
119119
def replacement(receiver, other)
120120
or_source = if other&.send_type?
121121
build_source_for_or_method(other)
122-
else
122+
elsif other.nil? || other.nil_type?
123123
''
124+
else
125+
" || #{other.source}"
124126
end
125127

126128
"#{receiver.source}.presence" + or_source

spec/rubocop/cop/rails/presence_spec.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@
3636
it_behaves_like 'offense', '!a.present? ? b : a', 'a.presence || b', 1, 1
3737
it_behaves_like 'offense', 'a.blank? ? b : a', 'a.presence || b', 1, 1
3838
it_behaves_like 'offense', '!a.blank? ? a : b', 'a.presence || b', 1, 1
39+
it_behaves_like 'offense', 'a.present? ? a : 1', 'a.presence || 1', 1, 1
40+
it_behaves_like 'offense', 'a.blank? ? 1 : a', 'a.presence || 1', 1, 1
3941

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

0 commit comments

Comments
 (0)