Skip to content

Commit 73bae13

Browse files
committed
[Fix #1565] Make Rails/Presence allow index access methods
This PR makes `Rails/Presence` allow index access methods. Fixes #1565.
1 parent ac34a8b commit 73bae13

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1565](https://github.com/rubocop/rubocop-rails/issues/1565): Make `Rails/Presence` allow index access methods. ([@koic][])

lib/rubocop/cop/rails/presence.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ class Presence < Base
6868
extend AutoCorrector
6969

7070
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
71+
INDEX_ACCESS_METHODS = %i[[] []=].freeze
7172

7273
def_node_matcher :redundant_receiver_and_other, <<~PATTERN
7374
{
@@ -140,7 +141,7 @@ def ignore_other_node?(node)
140141
end
141142

142143
def ignore_chain_node?(node)
143-
node.method?('[]') || node.method?('[]=') || node.arithmetic_operation? || node.comparison_method?
144+
index_access_method?(node) || node.assignment? || node.arithmetic_operation? || node.comparison_method?
144145
end
145146

146147
def message(node, replacement)
@@ -190,6 +191,10 @@ def chain_replacement(receiver, chain, left_sibling)
190191
replaced += "(#{chain.arguments.map(&:source).join(', ')})" if chain.arguments?
191192
left_sibling ? "(#{replaced})" : replaced
192193
end
194+
195+
def index_access_method?(node)
196+
INDEX_ACCESS_METHODS.include?(node.method_name)
197+
end
193198
end
194199
end
195200
end

spec/rubocop/cop/rails/presence_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,12 @@
301301
RUBY
302302
end
303303

304+
it 'does not register an offense when chained method is attribute assignment' do
305+
expect_no_offenses(<<~RUBY)
306+
a.attribute = 42 if a.present?
307+
RUBY
308+
end
309+
304310
it 'does not register an offense when chained method is an arithmetic operation' do
305311
expect_no_offenses(<<~RUBY)
306312
a.present? ? a + 42 : nil

0 commit comments

Comments
 (0)