Class: Blogo::Paginator
- Inherits:
-
Object
- Object
- Blogo::Paginator
- Defined in:
- lib/blogo/paginator.rb
Overview
Does main calculation for pagination.
Constant Summary collapse
- DEFAULT_PER_PAGE =
:nodoc:
10
- DEFAULT_PAGE =
:nodoc:
1
- DEFAULT_SIZE =
:nodoc:
5
Instance Attribute Summary collapse
-
#page ⇒ Object
readonly
Returns the value of attribute page.
-
#per_page ⇒ Object
readonly
Returns the value of attribute per_page.
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#initialize(relation, opts = {}) ⇒ Paginator
constructor
A new instance of Paginator.
-
#items ⇒ Array<ActiveRecord::Base>
Fetch items for the current page.
-
#next_page ⇒ Integer?
Next page number.
-
#pages ⇒ Array<Integer>
Number of pages to display.
-
#prev_page ⇒ Integer?
Previous page number.
Constructor Details
#initialize(relation, opts = {}) ⇒ Paginator
Returns a new instance of Paginator.
37 38 39 40 41 42 |
# File 'lib/blogo/paginator.rb', line 37 def initialize(relation, opts = {}) @relation = relation @per_page = (opts[:per_page] || DEFAULT_PER_PAGE).to_i @page = (opts[:page] || DEFAULT_PAGE).to_i @size = (opts[:size] || DEFAULT_SIZE).to_i end |
Instance Attribute Details
#page ⇒ Object (readonly)
Returns the value of attribute page.
21 22 23 |
# File 'lib/blogo/paginator.rb', line 21 def page @page end |
#per_page ⇒ Object (readonly)
Returns the value of attribute per_page.
21 22 23 |
# File 'lib/blogo/paginator.rb', line 21 def per_page @per_page end |
#size ⇒ Object (readonly)
Returns the value of attribute size.
21 22 23 |
# File 'lib/blogo/paginator.rb', line 21 def size @size end |
Instance Method Details
#items ⇒ Array<ActiveRecord::Base>
Fetch items for the current page.
47 48 49 50 51 52 |
# File 'lib/blogo/paginator.rb', line 47 def items @items ||= begin offset = @per_page * (@page - 1) @relation.limit(@per_page).offset(offset) end end |
#next_page ⇒ Integer?
Next page number. I used for >> link.
86 87 88 89 90 |
# File 'lib/blogo/paginator.rb', line 86 def next_page if pages.any? && pages_count > pages.last pages.last + 1 end end |
#pages ⇒ Array<Integer>
Number of pages to display.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/blogo/paginator.rb', line 57 def pages @pages ||= begin from = @page - (@size / 2).ceil from = 1 if from < 1 upto = from + @size - 1 # Correct +from+ and +to+ if +to+ is more than number of pages if upto > pages_count from -= (upto - pages_count) from = 1 if from < 1 upto = pages_count end (from..upto).to_a end end |
#prev_page ⇒ Integer?
Previous page number. Is used for << link.
77 78 79 80 |
# File 'lib/blogo/paginator.rb', line 77 def prev_page first_page = pages.first.to_i first_page > 1 ? (first_page - 1) : nil end |