Class Webby::Paginator
In: lib/webby/stelan/paginator.rb
Parent: Object

Methods

each   first   last   new   number_of_pages   page   reset  

Included Modules

Enumerable

Classes and Modules

Class Webby::Paginator::ArgumentError
Class Webby::Paginator::MissingCountError
Class Webby::Paginator::MissingSelectError
Class Webby::Paginator::Page

Attributes

count  [R] 
directory  [R] 
filename  [R] 
per_page  [R] 
resource  [R] 

Public Class methods

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)

[Source]

# File lib/webby/stelan/paginator.rb, line 32
  def initialize(count, per_page, resource, &select)
    @count, @per_page, @resource = count, per_page, resource
    @meta_data = @resource._meta_data.dup
    @filename = @resource.filename
    @directory = @resource.directory
    unless select
      raise MissingSelectError, "Must provide block to select data for each page"
    end
    @select = select
  end

Public Instance methods

[Source]

# File lib/webby/stelan/paginator.rb, line 58
  def each
    1.upto(number_of_pages) do |number|
      yield page(number)
    end
  end

First page object

[Source]

# File lib/webby/stelan/paginator.rb, line 49
  def first
    page 1
  end

Last page object

[Source]

# File lib/webby/stelan/paginator.rb, line 54
  def last
    page number_of_pages
  end

Total number of pages

[Source]

# File lib/webby/stelan/paginator.rb, line 44
  def number_of_pages
     (@count / @per_page).to_i + (@count % @per_page > 0 ? 1 : 0)
  end

Retrieve page object by number

[Source]

# File lib/webby/stelan/paginator.rb, line 65
  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

Finalizer method that should be called when the paginator is finished

[Source]

# File lib/webby/stelan/paginator.rb, line 76
  def reset
    resource._reset(@meta_data)
  end

[Validate]