Skip to content

Commit

Permalink
feat: add count and size to collection
Browse files Browse the repository at this point in the history
  • Loading branch information
marcosgz committed Jul 29, 2024
1 parent 067b7e3 commit 827e830
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/esse/active_record/collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ def each_batch_ids
end
end

def count
dataset.except(:includes, :preload, :eager_load).count
end
alias_method :size, :count

def dataset(**kwargs)
query = self.class.base_scope&.call || raise(NotImplementedError, "No scope defined for #{self.class}")
query = query.except(:order, :limit, :offset)
Expand Down
16 changes: 16 additions & 0 deletions spec/esse/active_record/collection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,22 @@
end
end

describe '#count' do
it 'raises NotImplementedError when scope is not defined on the collection class' do
expect {
collection = described_class.new
collection.count
}.to raise_error(NotImplementedError)
end

it 'returns the count of the dataset' do
collection = Class.new(described_class)
collection.base_scope = -> { Animal.all }
expect(collection.new.count).to eq(Animal.count)
expect(collection.new.size).to eq(Animal.count)
end
end

describe '#dataset' do
it 'returns an ActiveRecord::Relation' do
collection = Class.new(described_class)
Expand Down

0 comments on commit 827e830

Please sign in to comment.