Skip to content

Commit

Permalink
Support Rails 7.2 counter_cache configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
theodorton committed Aug 15, 2024
1 parent 9b2684c commit 450e8c4
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ def description
def matches?(subject)
self.subject = ModelReflector.new(subject, name)

if option_verifier.correct_for_string?(
:counter_cache,
counter_cache,
)
if correct_value?
true
else
self.missing_option = "#{name} should have #{description}"
Expand All @@ -34,9 +31,42 @@ def matches?(subject)

attr_accessor :subject, :counter_cache, :name

def correct_value?
expected = normalize_value

if expected.is_a?(Hash)
option_verifier.correct_for_hash?(
:counter_cache,
expected,
)
else
option_verifier.correct_for_string?(
:counter_cache,
expected,
)
end
end

def option_verifier
@_option_verifier ||= OptionVerifier.new(subject)
end

def normalize_value
if Rails::VERSION::STRING >= '7.2'
case counter_cache
when true
{ active: true, column: nil }
when String, Symbol
{ active: true, column: counter_cache.to_s }
when Hash
{ active: true, column: nil }.merge(counter_cache)
else
raise ArgumentError, 'Invalid counter_cache option'
end
else
counter_cache
end
end
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,28 @@
expect(belonging_to_parent).not_to belong_to(:parent).counter_cache
end

if rails_version >= 7.2
it 'accepts :counter_cache with a hash' do
expect(belonging_to_parent(counter_cache: { active: true })).
to belong_to(:parent).counter_cache
end

it 'accepts :counter_cache with active false when passed' do
expect(belonging_to_parent(counter_cache: { active: false })).
to belong_to(:parent).counter_cache(active: false)
end

it 'rejects :counter_cache with active false when mismatch' do
expect(belonging_to_parent(counter_cache: { active: true })).
not_to belong_to(:parent).counter_cache(active: false)
end

it 'rejects :counter_cache with when column mismatch' do
expect(belonging_to_parent(counter_cache: { column: :attribute_count })).
not_to belong_to(:parent).counter_cache(true)
end
end

it 'accepts an association with a valid :inverse_of option' do
expect(belonging_to_with_inverse(:parent, :children)).
to belong_to(:parent).inverse_of(:children)
Expand Down

0 comments on commit 450e8c4

Please sign in to comment.