Class: SimplyPaginate::Paginator

Inherits:
Object
  • Object
show all
Defined in:
lib/simply_paginate/paginator.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, per_page = self.class.per_page) ⇒ Paginator

Returns a new instance of Paginator.



17
18
19
20
# File 'lib/simply_paginate/paginator.rb', line 17

def initialize(collection, per_page = self.class.per_page)
  @collection = collection
  @per_page = per_page
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



5
6
7
# File 'lib/simply_paginate/paginator.rb', line 5

def collection
  @collection
end

Class Method Details

.per_pageObject



13
14
15
# File 'lib/simply_paginate/paginator.rb', line 13

def self.per_page
  @@per_page
end

.per_page=(amount_per_page) ⇒ Object

Raises:



7
8
9
10
11
# File 'lib/simply_paginate/paginator.rb', line 7

def self.per_page=(amount_per_page)
  raise NotInRangeError.new("Amount per page should be greater than 0") unless amount_per_page > 0

  @@per_page = amount_per_page
end

Instance Method Details

#[](index) ⇒ Object



36
37
38
# File 'lib/simply_paginate/paginator.rb', line 36

def [](index)
  Page.new(index, @collection, @per_page) unless collection.empty? || index <= 0 || index > total_pages
end

#currentObject



55
56
57
# File 'lib/simply_paginate/paginator.rb', line 55

def current
  @current
end

#eachObject



59
60
61
62
63
64
65
66
67
# File 'lib/simply_paginate/paginator.rb', line 59

def each
  start

  while next? do
    yield current

    next!
  end
end

#firstObject

Basic Operations



24
25
26
# File 'lib/simply_paginate/paginator.rb', line 24

def first
  self[FIRST_PAGE_INDEX]
end

#lastObject



28
29
30
# File 'lib/simply_paginate/paginator.rb', line 28

def last
  self[total_pages]
end

#next!Object

Iteration

Raises:

  • (NoMethodError)


42
43
44
45
# File 'lib/simply_paginate/paginator.rb', line 42

def next!
  raise NoMethodError.new("You need to start before iterating") unless current
  @current = current.next
end

#next?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/simply_paginate/paginator.rb', line 47

def next?
  current != nil
end

#startObject



51
52
53
# File 'lib/simply_paginate/paginator.rb', line 51

def start
  @current = first
end

#total_pagesObject



32
33
34
# File 'lib/simply_paginate/paginator.rb', line 32

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