Sha256: 23dac5e77d26263afd3a4e5b11713d8e096efde42bb27eddbd0a9b7d39a71df5

Contents?: true

Size: 945 Bytes

Versions: 2

Compression:

Stored size: 945 Bytes

Contents

require "smart_paginate/paginate"

module SmartPaginate
  class PaginatingArray < Array
    attr_accessor :current_page, :per_page, :total_entries

    def paginate(options = {})
      page = SmartPaginate::Paginate.new(options.fetch(:page), options[:per_page])

      if page.offset <= length
        array = self.slice(page.offset, page.per_page)
      else
        # out of bounds, just create an empty array
        array = PaginatingArray.new
      end

      array.current_page = page.current_page
      array.per_page = page.per_page
      array.total_entries = length
      array
    end

    def next_page?
      (current_page * per_page) < total_entries
    end

    def previous_page?
      current_page > 1
    end

    def next_page
      current_page + 1 if next_page?
    end

    def previous_page
      current_page - 1 if previous_page?
    end

    def total_pages
      (total_entries / per_page.to_f).ceil
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
smart_paginate-0.2.1 lib/smart_paginate/paginating_array.rb
smart_paginate-0.2.0 lib/smart_paginate/paginating_array.rb