Skip to content

Commit

Permalink
Restrict DuplicateAssociation cop to ActiveRecord
Browse files Browse the repository at this point in the history
Previously this cop would run against all classes, which led to false
positives when the class was not descended from `ActiveRecord::Base`
and thus might have acceptable use cases for repeating association
declarations in ways that would not be acceptable in AR classes.
  • Loading branch information
mjankowski committed May 1, 2023
1 parent 8611336 commit 06bc1a4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/rubocop/cop/rails/duplicate_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class DuplicateAssociation < Base
include RangeHelp
extend AutoCorrector
include ClassSendNodeHelper
include ActiveRecordHelper

MSG = "Association `%<name>s` is defined multiple times. Don't repeat associations."

Expand All @@ -32,6 +33,8 @@ class DuplicateAssociation < Base
PATTERN

def on_class(class_node)
return unless active_record?(class_node.parent_class)

offenses(class_node).each do |name, nodes|
nodes.each do |node|
add_offense(node, message: format(MSG, name: name)) do |corrector|
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/duplicate_association_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,15 @@ class Post < ApplicationRecord
RUBY
end
end

describe 'a class that does not descend from activerecord' do
it 'does not register an offense' do
expect_no_offenses(<<-RUBY)
class Post < ActiveModel::Serializer
has_many :comments, key: :remarks, if: :formal_mode?
has_many :comments, key: :rejoinders, if: :debate_mode?
end
RUBY
end
end
end

0 comments on commit 06bc1a4

Please sign in to comment.