2011-04-21 13:57:12 -04:00
|
|
|
module Kaminari
|
|
|
|
# Kind of Array that can paginate
|
|
|
|
class PaginatableArray < Array
|
|
|
|
include Kaminari::ConfigurationMethods::ClassMethods
|
|
|
|
|
|
|
|
attr_internal_accessor :limit_value, :offset_value
|
|
|
|
|
2011-08-24 07:16:14 -04:00
|
|
|
# ==== Options
|
|
|
|
# * <tt>:limit</tt> - limit
|
|
|
|
# * <tt>:offset</tt> - offset
|
|
|
|
# * <tt>:total_count</tt> - total_count
|
|
|
|
def initialize(original_array, options = {})
|
|
|
|
@_original_array, @_limit_value, @_offset_value, @_total_count = original_array, (options[:limit] || default_per_page).to_i, options[:offset].to_i, options[:total_count]
|
2011-08-25 19:12:10 -04:00
|
|
|
|
2011-08-25 19:23:51 -04:00
|
|
|
if options[:limit] && options[:offset]
|
|
|
|
class << self
|
|
|
|
include Kaminari::PageScopeMethods
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-08-25 19:12:10 -04:00
|
|
|
if options[:total_count]
|
|
|
|
super original_array
|
|
|
|
else
|
|
|
|
super(original_array[@_offset_value, @_limit_value] || [])
|
|
|
|
end
|
2011-04-21 13:57:12 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# items at the specified "page"
|
|
|
|
def page(num = 1)
|
|
|
|
offset(limit_value * ([num.to_i, 1].max - 1))
|
|
|
|
end
|
|
|
|
|
|
|
|
# returns another chunk of the original array
|
|
|
|
def limit(num)
|
2011-08-24 07:16:14 -04:00
|
|
|
self.class.new @_original_array, :limit => num, :offset => @_offset_value, :total_count => @_total_count
|
2011-04-21 13:57:12 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# total item numbers of the original array
|
|
|
|
def total_count
|
2011-07-24 22:34:37 -04:00
|
|
|
@_total_count || @_original_array.count
|
2011-04-21 13:57:12 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# returns another chunk of the original array
|
|
|
|
def offset(num)
|
2011-08-25 19:23:51 -04:00
|
|
|
self.class.new @_original_array, :limit => @_limit_value, :offset => num, :total_count => @_total_count
|
2011-04-21 13:57:12 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# Wrap an Array object to make it paginatable
|
|
|
|
def self.paginate_array(array)
|
|
|
|
PaginatableArray.new array
|
|
|
|
end
|
|
|
|
end
|