Skip to content

Commit

Permalink
[Fix rubocop#776] Fix an incorrect autocorrect for Rails/Presence
Browse files Browse the repository at this point in the history
Fixes rubocop#776.

This PR fixes an incorrect autocorrect for `Rails/Presence`
when using arithmetic operation in `else` branch.
  • Loading branch information
koic committed Sep 15, 2022
1 parent 6b5424e commit a5f0b7c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -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][])
12 changes: 6 additions & 6 deletions lib/rubocop/cop/rails/presence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/rails/presence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit a5f0b7c

Please sign in to comment.