Skip to content

Commit e9daa98

Browse files
authored
Merge pull request #1560 from davidenglishmusic/presence-cop-comparison-assignment-false-positives
[Fix #1557] Fix false positives for Rails/Presence with comparison and assignment operators
2 parents b50f629 + 391f7a4 commit e9daa98

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1557](https://github.com/rubocop/rubocop-rails/issues/1557): Fix false positives for `Rails/Presence` with comparison and assignment operators. ([@davidenglishmusic][])

lib/rubocop/cop/rails/presence.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,16 @@ module Rails
5353
#
5454
# # good
5555
# a.presence&.foo
56+
#
57+
# # good
58+
# a.present? ? a[1] : nil
59+
#
60+
# # good
61+
# a[:key] = value if a.present?
62+
#
63+
# # good
64+
# a.present? ? a > 1 : nil
65+
# a <= 0 if a.present?
5666
class Presence < Base
5767
include RangeHelp
5868
extend AutoCorrector
@@ -130,7 +140,7 @@ def ignore_other_node?(node)
130140
end
131141

132142
def ignore_chain_node?(node)
133-
node.method?('[]') || node.arithmetic_operation?
143+
node.method?('[]') || node.method?('[]=') || node.arithmetic_operation? || node.comparison_method?
134144
end
135145

136146
def message(node, replacement)

spec/rubocop/cop/rails/presence_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,12 +295,30 @@
295295
RUBY
296296
end
297297

298+
it 'does not register an offense when chained method is `[]=`' do
299+
expect_no_offenses(<<~RUBY)
300+
a[1] = 1 if a.present?
301+
RUBY
302+
end
303+
298304
it 'does not register an offense when chained method is an arithmetic operation' do
299305
expect_no_offenses(<<~RUBY)
300306
a.present? ? a + 42 : nil
301307
RUBY
302308
end
303309

310+
it 'does not register an offense when using comparison operation in modifier if' do
311+
expect_no_offenses(<<~RUBY)
312+
a <= 0 if a.present?
313+
RUBY
314+
end
315+
316+
it 'does not register an offense when chained method is a comparison operation in ternary' do
317+
expect_no_offenses(<<~RUBY)
318+
a.present? ? a > 42 : nil
319+
RUBY
320+
end
321+
304322
it 'does not register an offense when multiple methods are chained' do
305323
expect_no_offenses(<<~RUBY)
306324
a.present? ? a.foo.bar : nil

0 commit comments

Comments
 (0)