Class: RKit::Pagination::Base

Inherits:
CollectionDelegator show all
Includes:
Enumerable
Defined in:
lib/r_kit/pagination/base.rb

Defined Under Namespace

Classes: Page

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#decorate, #decorated?, #need_decoration?, #to_grid

Methods inherited from CollectionDelegator

#method_missing

Methods inherited from SimpleDelegator

#===, getobj_attr_reader

Constructor Details

#initialize(collection, **options) ⇒ Base

TODO: should raise (todo custom error) an error if has “limit” or “offset” values



6
7
8
9
10
11
12
13
# File 'lib/r_kit/pagination/base.rb', line 6

def initialize collection, **options
  raise if collection.values.keys.include_one? [:limit, :offset]

  super collection

  @page = options[:page] || 1
  @per_page = options[:per_page] || RKit::Pagination.config.per_page[collection.klass]
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class CollectionDelegator

Instance Attribute Details

#pageObject

Returns the value of attribute page.



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

def page
  @page
end

#per_pageObject

Returns the value of attribute per_page.



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

def per_page
  @per_page
end

Instance Method Details

#each(&block) ⇒ Object



43
44
45
# File 'lib/r_kit/pagination/base.rb', line 43

def each &block
  limited_collection.each(&block)
end

#limitObject

TODO: limit & offset should raise a custom made error



26
27
28
# File 'lib/r_kit/pagination/base.rb', line 26

def limit
  raise
end

#limited_collectionObject



35
36
37
38
39
# File 'lib/r_kit/pagination/base.rb', line 35

def limited_collection
  @limited_collection ||= collection
    .limit(per_page)
    .offset((page-1) * per_page)
end

#next_pageObject



67
68
69
# File 'lib/r_kit/pagination/base.rb', line 67

def next_page
  pages.find{ |page| page.page == (self.page + 1) } || pages.last
end

#offsetObject



30
31
32
# File 'lib/r_kit/pagination/base.rb', line 30

def offset
  raise
end

#pagesObject



57
58
59
60
61
# File 'lib/r_kit/pagination/base.rb', line 57

def pages
  (1..total_pages).map do |page|
    RKit::Pagination::Base::Page.new self, page: page
  end
end

#paginated?Boolean

Returns:

  • (Boolean)


15
# File 'lib/r_kit/pagination/base.rb', line 15

def paginated?() true end

#previous_pageObject



63
64
65
# File 'lib/r_kit/pagination/base.rb', line 63

def previous_page
  pages.find{ |page| page.page == (self.page - 1) } || pages.first
end

#reverseObject



49
50
51
52
53
54
# File 'lib/r_kit/pagination/base.rb', line 49

def reverse
  reversed = limited_collection.reverse
  @limited_collection.clear.concat(reversed)
  
  self
end

#total_pagesObject



20
21
22
# File 'lib/r_kit/pagination/base.rb', line 20

def total_pages
  (collection.count / per_page.to_f).ceil
end