Last active
August 29, 2015 14:04
-
-
Save warmwaffles/16bacd6fd569b2084b8f to your computer and use it in GitHub Desktop.
This file contains 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
require 'json' | |
class Pagination | |
attr_reader :limit, :offset, :total | |
def initialize(options={}) | |
@limit = options[:per_page] ? options[:per_page] : options[:limit] | |
@offset = options[:page] ? (options[:page] * @limit) : options[:offset] | |
@total = options[:total_entries] ? options[:total_entries] : options[:total] | |
end | |
def total_pages | |
(total.to_f / limit.to_f).ceil | |
end | |
def current_page | |
(offset / limit) + 1 | |
end | |
def max_pages | |
(total / limit) | |
end | |
def next? | |
current_page < max_pages | |
end | |
def previous? | |
current_page > 0 | |
end | |
def first | |
Pagination.new({ | |
limit: limit, | |
offset: 0, | |
total: total | |
}) | |
end | |
def next | |
return nil unless next? | |
Pagination.new({ | |
limit: limit, | |
offset: limit + offset, | |
total: total | |
}) | |
end | |
def previous | |
return nil unless previous? | |
Pagination.new({ | |
limit: limit, | |
offset: offset - limit, | |
total: total | |
}) | |
end | |
def last | |
Pagination.new({ | |
limit: limit, | |
offset: max_pages - 1, | |
total: total | |
}) | |
end | |
def to_hash | |
{ | |
limit: limit, | |
offset: offset, | |
total: total | |
} | |
end | |
def to_will_paginate_params | |
{ | |
page: current_page, | |
per_page: limit | |
} | |
end | |
def to_json(*) | |
JSON.dump(to_hash) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍