Class: Paginator

Inherits:
Object show all
Defined in:
lib/active_scaffold/paginator.rb

Defined Under Namespace

Classes: ArgumentError, MissingCountError, MissingSelectError, Page

Constant Summary collapse

VERSION =
'1.0.9'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

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)

Raises:


21
22
23
24
25
26
# File 'lib/active_scaffold/paginator.rb', line 21

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

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count


10
11
12
# File 'lib/active_scaffold/paginator.rb', line 10

def count
  @count
end

#per_pageObject (readonly)

Returns the value of attribute per_page


10
11
12
# File 'lib/active_scaffold/paginator.rb', line 10

def per_page
  @per_page
end

Instance Method Details

#eachObject

Iterate through pages


44
45
46
47
48
# File 'lib/active_scaffold/paginator.rb', line 44

def each
  each_with_index do |item, _|
    yield item
  end
end

#each_with_indexObject

Iterate through pages with indices


51
52
53
54
55
# File 'lib/active_scaffold/paginator.rb', line 51

def each_with_index
  1.upto(number_of_pages) do |number|
    yield(page(number), number - 1)
  end
end

#firstObject

First page object


34
35
36
# File 'lib/active_scaffold/paginator.rb', line 34

def first
  page 1
end

#lastObject

Last page object


39
40
41
# File 'lib/active_scaffold/paginator.rb', line 39

def last
  page number_of_pages
end

#number_of_pagesObject

Total number of pages


29
30
31
# File 'lib/active_scaffold/paginator.rb', line 29

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

#page(number) ⇒ Object

Retrieve page object by number


58
59
60
61
62
63
64
65
66
# File 'lib/active_scaffold/paginator.rb', line 58

def page(number)
  number = [1, number.to_i].max
  Page.new(self, number) do
    offset = (number - 1) * @per_page
    args = [offset]
    args << @per_page if @select.arity == 2
    @select.call(*args)
  end
end