Sha256: f6dfc926e43aae1c056e3fefc1e5459a5032de99e9c0dac6ac405a7db240cad1

Contents?: true

Size: 1.39 KB

Versions: 2

Compression:

Stored size: 1.39 KB

Contents

module SimplePagination
  class Page
    def initialize(number, collection)
      @number, @collection = number, collection
    end
    
    ##
    # The zero-based offset of the first record in this page
    def offset
      (@number-1) * @collection.page_size + 1
    end

    ##
    # The one-based page number for this page
    def number
      @number
    end

    ##
    # The Page object after this page (or +nil+ if +self.last?+)
    def next
      @collection[number + 1]
    end

    ##
    # The Page object before this page (or +nil+ if +self.first?+)
    def prev
      @collection[number - 1]
    end

    ##
    # Test if this is the first page in the collection
    def first?
      number == 1
    end

    ## 
    # Test if this is the last page in the collection
    def last?
      number == @collection.length
    end

    ##
    # Test if this is the current page.
    def current?
      self === @collection.current
    end

    ##
    # Generate a "window" of pages around (and including) this page. +n+
    # is the number of pages to show (defaults to 10).  For example, if this is
    # page 8 and you ask for window(10) you will get an array of Page objects
    # representing the following pages:  4, 5, 6, 7, 8, 9, 10, 11, 12, 13
    def window(n=10)
      start = [1, [number-(n/2)+1, @collection.length-n+1].min].max
      (start..start+n-1).collect {|i| @collection[i]}.compact
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
taylorbarstow-simple_pagination-0.1.0 lib/simple_pagination/page.rb
taylorbarstow-simple_pagination-0.1.1 lib/simple_pagination/page.rb