diff --git a/CHANGELOG.md b/CHANGELOG.md index 72cc17a2f5..67fa3d6d72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Bug fixes * [#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][]) +* [#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) diff --git a/lib/rubocop/cop/rails/presence.rb b/lib/rubocop/cop/rails/presence.rb index 73b9587269..20013392d3 100644 --- a/lib/rubocop/cop/rails/presence.rb +++ b/lib/rubocop/cop/rails/presence.rb @@ -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 diff --git a/spec/rubocop/cop/rails/presence_spec.rb b/spec/rubocop/cop/rails/presence_spec.rb index 304d83183b..27a5bf0612 100644 --- a/spec/rubocop/cop/rails/presence_spec.rb +++ b/spec/rubocop/cop/rails/presence_spec.rb @@ -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',