Skip to content

Commit

Permalink
Merge pull request #816 from ydah/fix/presence
Browse files Browse the repository at this point in the history
Fix an incorrect autocorrect for `Rails/Presence` when a right-hand side of the relational operator
  • Loading branch information
koic committed Oct 20, 2022
2 parents 7a434e4 + 4b6362e commit 25d9dfb
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#816](https://github.com/rubocop/rubocop-rails/pull/816): Fix an incorrect autocorrect for `Rails/Presence` when a right-hand side of the relational operator. ([@ydah][])
9 changes: 5 additions & 4 deletions lib/rubocop/cop/rails/presence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def on_if(node)

def register_offense(node, receiver, other)
add_offense(node, message: message(node, receiver, other)) do |corrector|
corrector.replace(node.source_range, replacement(receiver, other))
corrector.replace(node.source_range, replacement(receiver, other, node.left_sibling))
end
end

Expand All @@ -106,7 +106,7 @@ def ignore_other_node?(node)
end

def message(node, receiver, other)
prefer = replacement(receiver, other).gsub(/^\s*|\n/, '')
prefer = replacement(receiver, other, node.left_sibling).gsub(/^\s*|\n/, '')
current = current(node).gsub(/^\s*|\n/, '')
format(MSG, prefer: prefer, current: current)
end
Expand All @@ -119,7 +119,7 @@ def current(node)
end
end

def replacement(receiver, other)
def replacement(receiver, other, left_sibling)
or_source = if other&.send_type?
build_source_for_or_method(other)
elsif other.nil? || other.nil_type?
Expand All @@ -128,7 +128,8 @@ def replacement(receiver, other)
" || #{other.source}"
end

"#{receiver.source}.presence" + or_source
replaced = "#{receiver.source}.presence#{or_source}"
left_sibling ? "(#{replaced})" : replaced
end

def build_source_for_or_method(other)
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/rails/presence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,25 @@
end
end

context 'when a right-hand side of the relational operator' do
%w[< > <= >= == !=].each do |operator|
it "registers an offense and corrects when `#{operator}`" do
expect_offense(<<~RUBY, operator: operator)
a #{operator} if b.present?
_{operator} ^^^^^^^^^^^^^ Use `(b.presence || c)` instead of `if b.present? ... end`.
b
else
c
end
RUBY

expect_correction(<<~RUBY)
a #{operator} (b.presence || c)
RUBY
end
end
end

it 'does not register an offense when using `#presence`' do
expect_no_offenses(<<~RUBY)
a.presence
Expand Down

0 comments on commit 25d9dfb

Please sign in to comment.