Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1557](https://github.com/rubocop/rubocop-rails/issues/1557): Fix false positives for `Rails/Presence` with comparison and assignment operators. ([@davidenglishmusic][])
12 changes: 11 additions & 1 deletion lib/rubocop/cop/rails/presence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ module Rails
#
# # good
# a.presence&.foo
#
# # good
# a.present? ? a[1] : nil
#
# # good
# a[:key] = value if a.present?
#
# # good
# a.present? ? a > 1 : nil
# a <= 0 if a.present?
class Presence < Base
include RangeHelp
extend AutoCorrector
Expand Down Expand Up @@ -130,7 +140,7 @@ def ignore_other_node?(node)
end

def ignore_chain_node?(node)
node.method?('[]') || node.arithmetic_operation?
node.method?('[]') || node.method?('[]=') || node.arithmetic_operation? || node.comparison_method?
end

def message(node, replacement)
Expand Down
18 changes: 18 additions & 0 deletions spec/rubocop/cop/rails/presence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -295,12 +295,30 @@
RUBY
end

it 'does not register an offense when chained method is `[]=`' do
expect_no_offenses(<<~RUBY)
a[1] = 1 if a.present?
RUBY
end

it 'does not register an offense when chained method is an arithmetic operation' do
expect_no_offenses(<<~RUBY)
a.present? ? a + 42 : nil
RUBY
end

it 'does not register an offense when using comparison operation in modifier if' do
expect_no_offenses(<<~RUBY)
a <= 0 if a.present?
RUBY
end

it 'does not register an offense when chained method is a comparison operation in ternary' do
expect_no_offenses(<<~RUBY)
a.present? ? a > 42 : nil
RUBY
end

it 'does not register an offense when multiple methods are chained' do
expect_no_offenses(<<~RUBY)
a.present? ? a.foo.bar : nil
Expand Down