Skip to content

Commit

Permalink
fix paginated Relation count & empty? methods
Browse files Browse the repository at this point in the history
closes mislav#145
  • Loading branch information
mislav committed Aug 3, 2011
1 parent 16636f5 commit 2b96781
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
29 changes: 23 additions & 6 deletions lib/will_paginate/active_record.rb
Expand Up @@ -64,17 +64,25 @@ def total_entries
if loaded? and size < limit_value and (current_page == 1 or size > 0)
offset_value + size
else
excluded = [:order, :limit, :offset]
excluded << :includes unless eager_loading?
rel = self.except(*excluded)
# TODO: hack. decide whether to keep
rel = rel.apply_finder_options(@wp_count_options) if defined? @wp_count_options
@total_entries_queried = true
rel.count
count
end
end
end

def count
if limit_value
excluded = [:order, :limit, :offset]
excluded << :includes unless eager_loading?
rel = self.except(*excluded)
# TODO: hack. decide whether to keep
rel = rel.apply_finder_options(@wp_count_options) if defined? @wp_count_options
rel.count
else
super
end
end

# workaround for Active Record 3.0
def size
if !loaded? and limit_value
Expand All @@ -84,6 +92,15 @@ def size
end
end

# overloaded to be pagination-aware
def empty?
if !loaded? and offset_value
count <= offset_value
else
super
end
end

def total_pages
(total_entries / limit_value.to_f).ceil
end
Expand Down
27 changes: 20 additions & 7 deletions spec/finders/active_record_spec.rb
Expand Up @@ -53,6 +53,19 @@
rel.per_page.should == 5
end

it "remembers pagination in sub-relations" do
rel = Topic.paginate(:page => 2, :per_page => 3)
lambda {
rel.total_entries.should == 4
}.should run_queries(1)
rel = rel.mentions_activerecord
rel.current_page.should == 2
rel.per_page.should == 3
lambda {
rel.total_entries.should == 1
}.should run_queries(1)
end

it "supports the page() method" do
rel = Developer.page('1').order('id')
rel.current_page.should == 1
Expand Down Expand Up @@ -82,13 +95,6 @@
end

describe "counting" do
it "should not accept :count parameter" do
pending
lambda {
User.paginate :page => 1, :count => {}
}.should raise_error(ArgumentError)
end

it "should guess the total count" do
lambda {
topics = Topic.paginate :page => 2, :per_page => 3
Expand All @@ -111,6 +117,13 @@
}.should run_queries(2)
end

it "supports empty? method" do
topics = Topic.paginate :page => 1, :per_page => 3
lambda {
topics.should_not be_empty
}.should run_queries(1)
end

it "overrides total_entries count with a fixed value" do
lambda {
topics = Topic.paginate :page => 1, :per_page => 3, :total_entries => 999
Expand Down

0 comments on commit 2b96781

Please sign in to comment.