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:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/pagination/collection.rb', line 12

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 InvalidPage.new(@current_page) if @current_page < 1
  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))

  raise InvalidPage.new(current_page, total_pages) if current_page > total_pages
end

Instance Attribute Details

#current_pageObject (readonly)

Returns the value of attribute current_page.



10
11
12
# File 'lib/pagination/collection.rb', line 10

def current_page
  @current_page
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



10
11
12
# File 'lib/pagination/collection.rb', line 10

def per_page
  @per_page
end

#total_entriesObject

Returns the value of attribute total_entries.



10
11
12
# File 'lib/pagination/collection.rb', line 10

def total_entries
  @total_entries
end

#total_pagesObject (readonly)

Returns the value of attribute total_pages.



10
11
12
# File 'lib/pagination/collection.rb', line 10

def total_pages
  @total_pages
end

Instance Method Details

#next_pageObject



37
38
39
# File 'lib/pagination/collection.rb', line 37

def next_page
  current_page + 1 if current_page < total_pages
end

#offsetObject



41
42
43
# File 'lib/pagination/collection.rb', line 41

def offset
  offset = (current_page-1)*limit
end

#previous_pageObject



33
34
35
# File 'lib/pagination/collection.rb', line 33

def previous_page
  current_page - 1 if current_page > 1
end