Skip to content

Instantly share code, notes, and snippets.

@clausti
Last active September 24, 2020 18:37
Show Gist options
  • Save clausti/50fb82aed7d9b4b3c13403944345f613 to your computer and use it in GitHub Desktop.
Save clausti/50fb82aed7d9b4b3c13403944345f613 to your computer and use it in GitHub Desktop.
# app/controllers/concerns/pageable.rb
module Pageable
extend ActiveSupport::Concern
@@page_size = 20
def page
@page ||= (params[:page].to_i > 1) ? params[:page].to_i : 1
end
def pageable_query(pageable_relation)
@pageable_count = pageable_relation.count
pageable_relation.offset((page - 1) * @@page_size).limit(@@page_size)
end
def pageable_count
@pageable_count
end
def total_pages
@total_pages ||= (pageable_count.to_f / @@page_size).ceil
end
def next_page
@next_page ||= page + 1 if (page + 1) <= total_pages
end
def prev_page
@prev_page ||= page - 1 if (page - 1) > 0
end
def pageable_params
# The including controller should define this as non-empty if there are any params that are important to
# be passed from page to page eg topic.
{}
end
included do
helper_method :page_size, :pageable_count, :total_pages, :next_page, :prev_page, :page, :pageable_params
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment