module RokuPages::Pagination

Public Instance Methods

paginate(options) click to toggle source
# File lib/roku_pages.rb, line 3
def paginate(options)
  page = options[:page] || params[:page] || paginate_page
  per_page = options[:per_page] || params[:per_page] || paginate_per_page
  if %w(json xml).include?(request.format)
    respond_format = "#{request.format}".split('/').last.to_sym
  else
    raise 'roku_pages: unsupported format.'
  end

  collection = options[:json] || options[:xml]

  if collection.is_a?(Array)
    collection = Kaminari.paginate_array(collection)
  end

  if collection.is_a?(Array) || collection.is_a?(ActiveRecord::Relation)
    collection = collection.page(page).per(per_page)
    options.delete(:xml)
    options.delete(:json)
    options[respond_format] = collection

    pages_key = paginate_hash

    pages = {}
    pages[pages_key[:first]] = 1
    pages[pages_key[:prev]] = collection.current_page - 1 > 1 ? collection.current_page - 1 : 1
    pages[pages_key[:current]] = collection.current_page
    pages[pages_key[:next]] = collection.current_page + 1 < collection.total_pages ? collection.current_page + 1 : collection.total_pages
    pages[pages_key[:last]] = collection.total_pages
    pages[pages_key[:total]] = collection.total_count.to_s
    headers[paginate_root] = pages.to_json
  end

  render options
end
paginate_hash() click to toggle source
# File lib/roku_pages.rb, line 47
def paginate_hash
  {
      first: :first,
      prev: :prev,
      current: :current,
      next: :next,
      last: :last,
      total: :total
  }
end
paginate_page() click to toggle source
# File lib/roku_pages.rb, line 39
def paginate_page
  1
end
paginate_per_page() click to toggle source
# File lib/roku_pages.rb, line 43
def paginate_per_page
  25
end
paginate_root() click to toggle source
# File lib/roku_pages.rb, line 58
def paginate_root
  "Pagination"
end