Class: Pagination::Collection

Inherits:
Array
  • Object
show all
Defined in:
lib/pagination/collection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Collection

Returns a new instance of Collection.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/pagination/collection.rb', line 5

def initialize(options = {})
  @collection = options[:collection]

  if (already_paginated = ([:current_page, :per_page, :total_entries].all? { |m| @collection.respond_to?(m) }))
    @current_page = @collection.current_page
    @per_page = @collection.per_page
    self.total_entries ||= @collection.total_entries
  else
    @current_page = options[:current_page].to_i
    @per_page = options[:per_page].to_i
    self.total_entries ||= @collection.empty? ? 0 : @collection.count(:id , :distinct => true)
  end

  raise ArgumentError, "`per_page` setting cannot be less than 1 (#{@per_page} given)" if @per_page < 1

  replace(already_paginated ? @collection : @collection.paginate(:limit => limit, :offset => offset))
end

Instance Attribute Details

#current_pageObject (readonly)

Returns the value of attribute current_page.



3
4
5
# File 'lib/pagination/collection.rb', line 3

def current_page
  @current_page
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



3
4
5
# File 'lib/pagination/collection.rb', line 3

def per_page
  @per_page
end

#total_entriesObject

Returns the value of attribute total_entries.



3
4
5
# File 'lib/pagination/collection.rb', line 3

def total_entries
  @total_entries
end

#total_pagesObject (readonly)

Returns the value of attribute total_pages.



3
4
5
# File 'lib/pagination/collection.rb', line 3

def total_pages
  @total_pages
end

Instance Method Details

#next_pageObject



27
28
29
# File 'lib/pagination/collection.rb', line 27

def next_page
  current_page + 1 if current_page < total_pages
end

#offsetObject



31
32
33
# File 'lib/pagination/collection.rb', line 31

def offset
  ((current_page <= 0 ? 1 : current_page)-1)*limit
end

#previous_pageObject



23
24
25
# File 'lib/pagination/collection.rb', line 23

def previous_page
  current_page - 1 if current_page > 1
end