From a5f0b7cb1377f5762b915e96715bf3e15e989980 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 15 Sep 2022 20:52:53 +0900 Subject: [PATCH] [Fix #776] Fix an incorrect autocorrect for `Rails/Presence` Fixes #776. This PR fixes an incorrect autocorrect for `Rails/Presence` when using arithmetic operation in `else` branch. --- ...n_incorrect_autocorrect_for_rails_presence.md | 1 + lib/rubocop/cop/rails/presence.rb | 12 ++++++------ spec/rubocop/cop/rails/presence_spec.rb | 16 ++++++++++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 changelog/fix_an_incorrect_autocorrect_for_rails_presence.md diff --git a/changelog/fix_an_incorrect_autocorrect_for_rails_presence.md b/changelog/fix_an_incorrect_autocorrect_for_rails_presence.md new file mode 100644 index 0000000000..65a8a33062 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_rails_presence.md @@ -0,0 +1 @@ +* [#776](https://github.com/rubocop/rubocop-rails/pull/776): Fix an incorrect autocorrect for `Rails/Presence` when using arithmetic operation in `else` branch. ([@koic][]) diff --git a/lib/rubocop/cop/rails/presence.rb b/lib/rubocop/cop/rails/presence.rb index f9313ef75a..c89a5c6319 100644 --- a/lib/rubocop/cop/rails/presence.rb +++ b/lib/rubocop/cop/rails/presence.rb @@ -122,19 +122,19 @@ def replacement(receiver, other) end def build_source_for_or_method(other) - if other.parenthesized? || other.method?('[]') || !other.arguments? + if other.parenthesized? || other.method?('[]') || other.arithmetic_operation? || !other.arguments? " || #{other.source}" else - method = range_between( - other.source_range.begin_pos, - other.first_argument.source_range.begin_pos - 1 - ).source - + method = method_range(other).source arguments = other.arguments.map(&:source).join(', ') " || #{method}(#{arguments})" end end + + def method_range(node) + range_between(node.source_range.begin_pos, node.first_argument.source_range.begin_pos - 1) + end end end end diff --git a/spec/rubocop/cop/rails/presence_spec.rb b/spec/rubocop/cop/rails/presence_spec.rb index 3d4d1a8a67..50dfbfd776 100644 --- a/spec/rubocop/cop/rails/presence_spec.rb +++ b/spec/rubocop/cop/rails/presence_spec.rb @@ -49,6 +49,22 @@ end RUBY + it_behaves_like 'offense', <<~RUBY.chomp, 'a.presence || b.to_f + 12.0', 1, 5 + if a.present? + a + else + b.to_f + 12.0 + end + RUBY + + it_behaves_like 'offense', <<~RUBY.chomp, 'a.presence || b.to_f * 12.0', 1, 5 + if a.present? + a + else + b.to_f * 12.0 + end + RUBY + it_behaves_like 'offense', 'a if a.present?', 'a.presence', 1, 1 it_behaves_like 'offense', 'a unless a.blank?', 'a.presence', 1, 1 it_behaves_like 'offense', <<~RUBY.chomp, <<~FIXED.chomp, 1, 7