Class: Paginator::Pager

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/paginator/pager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count, per_page, &select) ⇒ Pager

Instantiate a new Paginator object

Provide:

  • A total count of the number of objects to paginate
  • The number of objects in each page
  • A block that returns the array of items
    • The block is passed the item offset (and the number of items to show per page, for convenience, if the arity is 2)


17
18
19
20
21
22
23
# File 'lib/paginator/pager.rb', line 17

def initialize(count, per_page, &select)
  @count, @per_page = count, per_page
  unless select
    raise MissingSelectError, "Must provide block to select data for each page"
  end
  @select = select
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



6
7
8
# File 'lib/paginator/pager.rb', line 6

def count
  @count
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



6
7
8
# File 'lib/paginator/pager.rb', line 6

def per_page
  @per_page
end

Instance Method Details

#each(&block) ⇒ Object



40
41
42
43
44
45
# File 'lib/paginator/pager.rb', line 40

def each(&block)
  return enum_for(:each) unless block_given?
  1.upto(number_of_pages) do |number|
    yield page(number)
  end
end

#firstObject

First page object



31
32
33
# File 'lib/paginator/pager.rb', line 31

def first
  page 1
end

#lastObject

Last page object



36
37
38
# File 'lib/paginator/pager.rb', line 36

def last
  page number_of_pages
end

#number_of_pagesObject

Total number of pages



26
27
28
# File 'lib/paginator/pager.rb', line 26

def number_of_pages
  (@count / @per_page).to_i + (@count % @per_page > 0 ? 1 : 0)
end

#page(number) ⇒ Object

Retrieve page object by number



48
49
50
51
52
53
54
55
56
# File 'lib/paginator/pager.rb', line 48

def page(number)
  number = (n = number.to_i) > 0 ? n : 1
  Page.new(self, number, lambda {
             offset = (number - 1) * @per_page
             args = [offset]
             args << @per_page if @select.arity == 2
             @select.call(*args)
           })
end