Class: SolidWebUi::Paginator
- Inherits:
-
Object
- Object
- SolidWebUi::Paginator
- 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
-
#page ⇒ Object
readonly
Returns the value of attribute page.
-
#per_page ⇒ Object
readonly
Returns the value of attribute per_page.
-
#total_count ⇒ Object
readonly
Returns the value of attribute total_count.
Instance Method Summary collapse
- #current_page ⇒ Object
- #first_page? ⇒ Boolean
-
#initialize(scope, page:, per_page: 25) ⇒ Paginator
constructor
A new instance of Paginator.
- #last_page? ⇒ Boolean
- #next_page ⇒ Object
- #offset ⇒ Object
- #prev_page ⇒ Object
- #records ⇒ Object
- #total_pages ⇒ Object
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
#page ⇒ Object (readonly)
Returns the value of attribute page.
8 9 10 |
# File 'lib/solid_web_ui/paginator.rb', line 8 def page @page end |
#per_page ⇒ Object (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_count ⇒ Object (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_page ⇒ Object
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
33 34 35 |
# File 'lib/solid_web_ui/paginator.rb', line 33 def first_page? current_page <= 1 end |
#last_page? ⇒ Boolean
37 38 39 |
# File 'lib/solid_web_ui/paginator.rb', line 37 def last_page? current_page >= total_pages end |
#next_page ⇒ Object
45 46 47 |
# File 'lib/solid_web_ui/paginator.rb', line 45 def next_page last_page? ? nil : current_page + 1 end |
#offset ⇒ Object
25 26 27 |
# File 'lib/solid_web_ui/paginator.rb', line 25 def offset (current_page - 1) * per_page end |
#prev_page ⇒ Object
41 42 43 |
# File 'lib/solid_web_ui/paginator.rb', line 41 def prev_page first_page? ? nil : current_page - 1 end |
#records ⇒ Object
29 30 31 |
# File 'lib/solid_web_ui/paginator.rb', line 29 def records @scope.limit(per_page).offset(offset) end |
#total_pages ⇒ Object
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 |