Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

fix paginated Relation `count` & `empty?` methods

closes #145
  • Loading branch information...
commit 2b96781a39099d7d4c4f31c869a1d686f98ab3a7 1 parent 16636f5
Mislav Marohnić mislav authored
29 lib/will_paginate/active_record.rb
View
@@ -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
@@ -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
27 spec/finders/active_record_spec.rb
View
@@ -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
@@ -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
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.