Created
March 20, 2014 19:54
-
-
Save cheeyeo/9672433 to your computer and use it in GitHub Desktop.
Ruby pagination example with extend
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
module Pagination | |
def paginate(page = 1, items_per_page = size, total_items = size) | |
@page = 1 | |
@items_per_page = items_per_page | |
@total_items = total_items | |
end | |
attr_reader :page, :items_per_page, :total_items | |
def total_pages | |
(total_items / items_per_page).ceil | |
end | |
end | |
collection = %w[first second third] | |
collection.extend(Pagination) | |
collection.paginate(1, 3, 10) | |
p "There are #{collection.total_pages} items." | |
p "The collection is an Array." if collection.is_a?(Array) | |
p "The collection is a paginated collection" if collection.is_a?(Pagination) | |
collection = {first: 1, second: 2, third: 3} | |
collection.extend(Pagination) | |
collection.paginate(1, 3, 10) | |
p "There are #{collection.total_pages} items." | |
p "The collection is an Hash." if collection.is_a?(Hash) | |
p "The collection is a paginated collection" if collection.is_a?(Pagination) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment