Created
September 4, 2014 06:44
-
-
Save he9lin/dd484a5a1231e730869c to your computer and use it in GitHub Desktop.
Simple Paginate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #= Paginated | |
| # | |
| # Usage: | |
| # | |
| # customers = store.customers.extend Paginated | |
| # customers.per_page(5) # defaults to 25 | |
| # customers.page(0) # returns an array | |
| # | |
| # count | |
| # where.limit | |
| # where.skip | |
| module Paginated | |
| @@default_per_page = 25 | |
| InvalidPageNumError = Class.new(StandardError) | |
| class << self | |
| def default_per_page=(num) | |
| @@default_per_page = num | |
| end | |
| end | |
| class Pagination | |
| attr_reader :total_pages, :current_page, :skip_items | |
| def initialize(total_items, per_page, current_page) | |
| @per_page = per_page | |
| @current_page = current_page | |
| @skip_items = current_page * per_page | |
| @total_pages = (total_items / per_page).ceil | |
| raise InvalidPageNumError, 'page asked for exceeds max page number' \ | |
| if @current_page > @total_pages - 1 | |
| end | |
| end | |
| def pagination | |
| @pagination | |
| end | |
| def page(page_num) | |
| per_page = @per_page || @@default_per_page | |
| @pagination = Pagination.new(where.count, per_page, page_num) | |
| where.limit(per_page).skip(@pagination.skip_items) | |
| end | |
| def per_page(num) | |
| @per_page = num | |
| end | |
| end | |
| class Customers | |
| def where | |
| Where.new | |
| end | |
| end | |
| class Where < Hash | |
| def count | |
| 1000 | |
| end | |
| def limit(num) | |
| self[:limit] = num | |
| self | |
| end | |
| def skip(num) | |
| self[:skip] = num | |
| self | |
| end | |
| end | |
| Paginated.default_per_page = 22 | |
| customers = Customers.new | |
| customers.extend Paginated | |
| p customers.page(1) | |
| p customers.pagination |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment