Skip to content

Commit

Permalink
Proxy class for Array which adds pagination methods
Browse files Browse the repository at this point in the history
  • Loading branch information
lardawge committed Jun 28, 2011
1 parent 9dc7cb7 commit ef699b7
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
52 changes: 52 additions & 0 deletions sunspot/lib/sunspot/collection.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
module Sunspot
class Collection
instance_methods.each { |m| undef_method m unless m =~ /^__|instance_eval|object_id/ }

attr_reader :total_count, :current_page, :per_page
alias :total_entries :total_count
alias :limit_value :per_page

def initialize collection, page, total, per_page
@collection = collection
@current_page = page
@per_page = per_page
@total_count = total
end

def total_pages
(total_count.to_f / per_page).ceil
end
alias :num_pages :total_pages

def first_page?
current_page == 1
end

def last_page?
current_page >= total_pages
end

def previous_page
current_page > 1 ? (current_page - 1) : nil
end

def next_page
current_page < total_pages ? (current_page + 1) : nil
end

def out_of_bounds?
current_page > total_pages
end

def offset
(current_page - 1) * per_page
end

private

def method_missing(method, *args, &block)
@collection.send(method, *args, &block)
end

end
end
27 changes: 27 additions & 0 deletions sunspot/spec/api/collection_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
require File.expand_path('spec_helper', File.dirname(__FILE__))
require 'sunspot/collection'

describe "Collection" do
subject { Sunspot::Collection.new [], 1, 20, 10 }

it { subject.should be_an(Array) }

context "behaves like a WillPaginate::Collection" do
it { subject.total_entries.should eql(20) }
it { subject.total_pages.should eql(2) }
it { subject.current_page.should eql(1) }
it { subject.per_page.should eql(10) }
it { subject.previous_page.should be_nil }
it { subject.next_page.should eql(2) }
it { subject.out_of_bounds?.should_not be_true }
it { subject.offset.should eql(0) }
end

context "behaves like Kaminari" do
it { subject.total_count.should eql(20) }
it { subject.num_pages.should eql(2) }
it { subject.limit_value.should eql(10) }
it { subject.first_page?.should be_true }
it { subject.last_page?.should_not be_true }
end
end

0 comments on commit ef699b7

Please sign in to comment.