Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Last active August 29, 2015 14:04
Show Gist options
  • Save warmwaffles/16bacd6fd569b2084b8f to your computer and use it in GitHub Desktop.
Save warmwaffles/16bacd6fd569b2084b8f to your computer and use it in GitHub Desktop.
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
@nateklaiber
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment