From b32dc36472553d4bb8cbdd142dc5f87331edfc02 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Tue, 27 Aug 2019 17:09:19 +0900 Subject: [PATCH] [#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 is auto-corrected to `a.presence || 1`. --- CHANGELOG.md | 4 ++++ lib/rubocop/cop/rails/presence.rb | 4 +++- spec/rubocop/cop/rails/presence_spec.rb | 2 ++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a8b16d585..0b5bff9709 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 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',