Skip to content

Commit

Permalink
add support for counting grouped collections (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
sliminas authored and ddnexus committed Jun 23, 2018
1 parent 70047eb commit 5863ceb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
7 changes: 4 additions & 3 deletions lib/pagy/backend.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ def pagy(collection, vars={})

# Sub-method called only by #pagy: here for easy customization of variables by overriding
def pagy_get_vars(collection, vars)
# Return the merged variables to initialize the Pagy object
{ count: collection.count(:all), # works with AR, but may not work with other ORMs
page: params[vars[:page_param]||VARS[:page_param]] }.merge!(vars)
count = collection.count(:all)
count = count.count if count.respond_to?(:count) # e.g. AR .group returns an OrderdHash that responds to #count
# return the merged variables to initialize the pagy object
{ count: count, page: params[vars[:page_param] || VARS[:page_param]] }.merge!(vars)
end

# Sub-method called only by #pagy: here for easy customization of record-extraction by overriding
Expand Down
15 changes: 14 additions & 1 deletion test/pagy/backend_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

describe Pagy::Backend do


let(:backend) { TestController.new }

describe "#pagy" do
Expand Down Expand Up @@ -66,6 +65,20 @@ def test_pagy_get_vars_with_vars
assert_equal('X', merged[:link_extra])
end

def test_pagy_get_vars_with_grouped_collection
@collection = GroupedCollection.new((1..1000).to_a)
vars = {page: 2, items: 10, link_extra: 'X'}
merged = backend.send :pagy_get_vars, @collection, vars
assert_includes(merged.keys, :count)
assert_includes(merged.keys, :page)
assert_includes(merged.keys, :items)
assert_includes(merged.keys, :link_extra)
assert_equal(1000, merged[:count])
assert_equal(2, merged[:page])
assert_equal(10, merged[:items])
assert_equal('X', merged[:link_extra])
end

end

describe "#pagy_get_items" do
Expand Down
8 changes: 8 additions & 0 deletions test/test_helper/backend.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,11 @@ def count(*_)
end

end

class GroupedCollection < TestCollection

def count(*_)
@collection.map { |value| [value, value + 1] }.to_h
end

end

0 comments on commit 5863ceb

Please sign in to comment.