class Thron::Paginator

Constants

MAX_LIMIT

Attributes

cache[R]
limit[R]
offset[R]

Public Class Methods

check_limit(limit) click to toggle source
# 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
new(options = {}) click to toggle source
# File lib/thron/paginator.rb, line 16
def initialize(options = {})
  body = options[:body]
  limit = options.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

Public Instance Methods

next() click to toggle source
# File lib/thron/paginator.rb, line 32
def next
  @offset = next_offset
  fetch.value
end
preload(n) click to toggle source
# 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() click to toggle source
# File lib/thron/paginator.rb, line 27
def prev
  @offset = prev_offset
  fetch.value
end
total() click to toggle source
# 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

Private Instance Methods

call(offset) click to toggle source
# File lib/thron/paginator.rb, line 62
def call(offset)
  Thread::new { @body.call(@limit, offset) }
end
fetch(offset = @offset) click to toggle source
# File lib/thron/paginator.rb, line 54
def fetch(offset = @offset)
  @cache.fetch(offset) do
    call(offset).tap do |raw|
      @cache[offset] = raw
    end
  end
end
max_offset() click to toggle source
# File lib/thron/paginator.rb, line 77
def max_offset
  return 0 if cache.empty?
  @cache.max.first
end
next_offset() click to toggle source
# File lib/thron/paginator.rb, line 66
def next_offset
  return 0 if cache.empty?
  return @offset if total > 0 && (@offset + @limit) >= total
  @offset + @limit
end
prev_offset() click to toggle source
# File lib/thron/paginator.rb, line 72
def prev_offset
  return 0 if @offset <= @limit
  @offset - @limit
end