Class: Thron::Paginator
- Inherits:
-
Object
- Object
- Thron::Paginator
- Defined in:
- lib/thron/paginator.rb
Constant Summary collapse
- MAX_LIMIT =
50
Instance Attribute Summary collapse
-
#cache ⇒ Object
readonly
Returns the value of attribute cache.
-
#limit ⇒ Object
readonly
Returns the value of attribute limit.
-
#offset ⇒ Object
readonly
Returns the value of attribute offset.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Paginator
constructor
A new instance of Paginator.
- #next ⇒ Object
- #preload(n) ⇒ Object
- #prev ⇒ Object
- #total ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Paginator
Returns a new instance of Paginator.
16 17 18 19 20 21 22 23 24 25 |
# File 'lib/thron/paginator.rb', line 16 def initialize( = {}) body = [:body] limit = .fetch(:limit) { MAX_LIMIT } fail ArgumentError, 'body must be a proc object' unless body.is_a?(Proc) fail ArgumentError, 'body must accept the limit and offset attributes' unless body.arity == 2 @body = body @limit = self.class.check_limit(limit) @offset = offset.to_i @cache = {} end |
Instance Attribute Details
#cache ⇒ Object (readonly)
Returns the value of attribute cache.
14 15 16 |
# File 'lib/thron/paginator.rb', line 14 def cache @cache end |
#limit ⇒ Object (readonly)
Returns the value of attribute limit.
14 15 16 |
# File 'lib/thron/paginator.rb', line 14 def limit @limit end |
#offset ⇒ Object (readonly)
Returns the value of attribute offset.
14 15 16 |
# File 'lib/thron/paginator.rb', line 14 def offset @offset end |
Class Method Details
.check_limit(limit) ⇒ Object
8 9 10 11 12 |
# File 'lib/thron/paginator.rb', line 8 def self.check_limit(limit) limit.to_i.tap do |limit| return MAX_LIMIT if limit > MAX_LIMIT end end |
Instance Method Details
#next ⇒ Object
32 33 34 35 |
# File 'lib/thron/paginator.rb', line 32 def next @offset = next_offset fetch.value end |
#preload(n) ⇒ Object
37 38 39 40 41 42 43 44 |
# File 'lib/thron/paginator.rb', line 37 def preload(n) starting_offset = max_offset (n).to_i.times do |i| index = starting_offset.zero? ? i : (i + 1) offset = starting_offset + (index * @limit) fetch(offset) end end |
#prev ⇒ Object
27 28 29 30 |
# File 'lib/thron/paginator.rb', line 27 def prev @offset = prev_offset fetch.value end |
#total ⇒ Object
46 47 48 49 50 |
# File 'lib/thron/paginator.rb', line 46 def total return @total if @total return 0 if cache.empty? @total = cache.fetch(0).value.total end |