Skip to content

Instantly share code, notes, and snippets.

@timriley
Created January 12, 2016 23:00
Show Gist options
  • Save timriley/bce3340ee78238ed2782 to your computer and use it in GitHub Desktop.
Save timriley/bce3340ee78238ed2782 to your computer and use it in GitHub Desktop.
Rodakase/ROM pagination
nav.pagination
- unless first_page?
span.first
a href=url_for_page(1)
| « First
span.prev
a href=url_for_page(prev_page) rel="prev"
| ‹ Prev
- if prev_gap?
span.page.gap
| …
- each_entry do |page|
span.page class=("current" if page.current?)
a href=url_for_page(page) = page.number
- if next_gap?
span.page.gap
| …
- unless last_page?
span.next
a href=url_for_page(next_page) rel="next"
| Next ›
span.last
a href=url_for_page(last_page)
| Last »
require "main/view"
require "main/paginator"
module Main
module Views
module Articles
class Index < Main::View
include Main::Import("main.persistence.repositories.articles")
configure do |config|
config.template = "articles/index"
end
def locals(per_page: 10, page: 1)
latest_articles = articles.index(per_page: per_page, page: page)
{
articles: latest_articles,
paginator: Main::Paginator.new(latest_articles.pager, url_template: "/articles?page=%")
}
end
end
end
end
end
h1 Articles
- articles.each do |article|
/ blah blah
== paginator.pagination
require "forwardable"
module Main
class Paginator
class Entry
attr_reader :number
def initialize(number, current:)
@number = number
@current = current
end
def to_s
number.to_s
end
def current?
!!@current
end
end
extend Forwardable
def_delegators :@pager,
:current_page,
:per_page,
:next_page,
:prev_page,
:total,
:total_pages
# @api private
attr_reader :url_template
attr_reader :buffer
def initialize(pager, url_template:, buffer: 2)
@pager = pager
@url_template = url_template
@buffer = buffer
# byebug
end
def first_page
1
end
def first_page?
current_page == first_page
end
def last_page
total_pages
end
def last_page?
current_page == last_page
end
def prev_gap?
current_page - buffer > first_page
end
def next_gap?
current_page + buffer < last_page
end
def each_entry
return to_enum(:each_entry) unless block_given?
entry_numbers.each do |number|
yield Entry.new(number, current: number == current_page)
end
end
def url_for_page(page)
url_template.tr("%", page.to_s)
end
private
def entry_numbers
left_edge = current_page - buffer
left_edge = 1 if left_edge < 1
right_edge = current_page + buffer
right_edge = total_pages if right_edge > total_pages
left_edge.upto(right_edge).to_a
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment