Class: SolidWebUi::Paginator

Inherits:
Object
  • Object
show all
Defined in:
lib/solid_web_ui/paginator.rb

Overview

Tiny offset paginator so the gems don’t take a hard dependency on kaminari/pagy. Works with any object responding to #count, #limit and #offset (an ActiveRecord::Relation), or with a precomputed Integer count.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, page:, per_page: 25) ⇒ Paginator

Returns a new instance of Paginator.



10
11
12
13
14
15
# File 'lib/solid_web_ui/paginator.rb', line 10

def initialize(scope, page:, per_page: 25)
  @scope = scope
  @per_page = [ per_page.to_i, 1 ].max
  @total_count = scope.is_a?(Integer) ? scope : scope.count
  @page = [ page.to_i, 1 ].max
end

Instance Attribute Details

#pageObject (readonly)

Returns the value of attribute page.



8
9
10
# File 'lib/solid_web_ui/paginator.rb', line 8

def page
  @page
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



8
9
10
# File 'lib/solid_web_ui/paginator.rb', line 8

def per_page
  @per_page
end

#total_countObject (readonly)

Returns the value of attribute total_count.



8
9
10
# File 'lib/solid_web_ui/paginator.rb', line 8

def total_count
  @total_count
end

Instance Method Details

#current_pageObject



21
22
23
# File 'lib/solid_web_ui/paginator.rb', line 21

def current_page
  [ [ page, total_pages ].min, 1 ].max
end

#first_page?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/solid_web_ui/paginator.rb', line 33

def first_page?
  current_page <= 1
end

#last_page?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/solid_web_ui/paginator.rb', line 37

def last_page?
  current_page >= total_pages
end

#next_pageObject



45
46
47
# File 'lib/solid_web_ui/paginator.rb', line 45

def next_page
  last_page? ? nil : current_page + 1
end

#offsetObject



25
26
27
# File 'lib/solid_web_ui/paginator.rb', line 25

def offset
  (current_page - 1) * per_page
end

#prev_pageObject



41
42
43
# File 'lib/solid_web_ui/paginator.rb', line 41

def prev_page
  first_page? ? nil : current_page - 1
end

#recordsObject



29
30
31
# File 'lib/solid_web_ui/paginator.rb', line 29

def records
  @scope.limit(per_page).offset(offset)
end

#total_pagesObject



17
18
19
# File 'lib/solid_web_ui/paginator.rb', line 17

def total_pages
  [ (total_count.to_f / per_page).ceil, 1 ].max
end