Skip to content
Open
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 @@
* [#1565](https://github.com/rubocop/rubocop-rails/issues/1565): Make `Rails/Presence` allow index access methods. ([@koic][])
7 changes: 6 additions & 1 deletion lib/rubocop/cop/rails/presence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class Presence < Base
extend AutoCorrector

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

def_node_matcher :redundant_receiver_and_other, <<~PATTERN
{
Expand Down Expand Up @@ -140,7 +141,7 @@ def ignore_other_node?(node)
end

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

def message(node, replacement)
Expand Down Expand Up @@ -190,6 +191,10 @@ def chain_replacement(receiver, chain, left_sibling)
replaced += "(#{chain.arguments.map(&:source).join(', ')})" if chain.arguments?
left_sibling ? "(#{replaced})" : replaced
end

def index_access_method?(node)
INDEX_ACCESS_METHODS.include?(node.method_name)
end
end
end
end
Expand Down
6 changes: 6 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,12 @@
RUBY
end

it 'does not register an offense when chained method is attribute assignment' do
expect_no_offenses(<<~RUBY)
a.attribute = 42 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
Expand Down