Class: Perron::Paginate

Inherits:
Object
  • Object
show all
Defined in:
lib/perron/paginate.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, page:, per_page:, base_path: nil, page_path_template: nil, use_query_params: false) ⇒ Paginate

Returns a new instance of Paginate.



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/perron/paginate.rb', line 5

def initialize(collection, page:, per_page:, base_path: nil, page_path_template: nil, use_query_params: false)
  @collection = collection
  @per_page = per_page
  @base_path = base_path
  @page_path_template = page_path_template || "/page/:page/"
  @use_query_params = use_query_params

  @total_items = collection.size
  @total_pages = total_items.zero? ? 0 : (total_items.to_f / per_page).ceil
  @current_page = page.clamp(1, total_pages.zero? ? 1 : total_pages)
end

Instance Attribute Details

#current_pageObject (readonly)

Returns the value of attribute current_page.



17
18
19
# File 'lib/perron/paginate.rb', line 17

def current_page
  @current_page
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



17
18
19
# File 'lib/perron/paginate.rb', line 17

def per_page
  @per_page
end

#total_itemsObject (readonly)

Returns the value of attribute total_items.



17
18
19
# File 'lib/perron/paginate.rb', line 17

def total_items
  @total_items
end

#total_pagesObject (readonly)

Returns the value of attribute total_pages.



17
18
19
# File 'lib/perron/paginate.rb', line 17

def total_pages
  @total_pages
end

Instance Method Details

#itemsObject



19
20
21
22
23
# File 'lib/perron/paginate.rb', line 19

def items
  offset = (@current_page - 1) * @per_page

  @collection[offset, @per_page] || []
end

#nextObject



29
30
31
32
33
# File 'lib/perron/paginate.rb', line 29

def next
  return unless next?

  page_path(@current_page + 1)
end

#next?Boolean

Returns:

  • (Boolean)


25
# File 'lib/perron/paginate.rb', line 25

def next? = @current_page < @total_pages

#previousObject



35
36
37
38
39
40
41
# File 'lib/perron/paginate.rb', line 35

def previous
  return unless previous?

  target = (@current_page == 2) ? 1 : @current_page - 1

  page_path(target)
end

#previous?Boolean

Returns:

  • (Boolean)


27
# File 'lib/perron/paginate.rb', line 27

def previous? = @current_page > 1