Class: Ludy::Paginator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/ludy/paginator.rb

Overview

paginator is something help you paginate the data, through the fetcher and counter you pass in. e.g., for a array, the fetcher would be array[offset, per_page], the counter would be array.size. and for rails’ model, fetcher would be Model.find :all, :offset => offset, :limit => per_page. see ArrayPaginator and RailsPaginator, if you just simply need them or have a look at the source code for example usage for Paginator.

Direct Known Subclasses

ArrayPaginator, RailsPaginator

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fetcher, counter) ⇒ Paginator

fetcher is function that fetch the data,

counter is function that count the data.

the default per_page is 20. you can reset per_page property later.



55
56
57
58
59
# File 'lib/ludy/paginator.rb', line 55

def initialize fetcher, counter
  @per_page = 20
  @fetcher = fetcher
  @counter = counter
end

Instance Attribute Details

#counterObject

Returns the value of attribute counter.



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

def counter
  @counter
end

#fetcherObject

Returns the value of attribute fetcher.



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

def fetcher
  @fetcher
end

#per_pageObject

Returns the value of attribute per_page.



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

def per_page
  @per_page
end

Instance Method Details

#==(rhs) ⇒ Object

if two paginators are equal, then the properties of per_page, fetcher, counter are all equal.



62
63
64
65
66
# File 'lib/ludy/paginator.rb', line 62

def == rhs
  self.per_page == rhs.per_page and
  self.fetcher  == rhs.fetcher  and
  self.counter  == rhs.counter
end

#countObject

simply call @counter.call



83
# File 'lib/ludy/paginator.rb', line 83

def count; @counter.call; end

#eachObject

for each page…



68
# File 'lib/ludy/paginator.rb', line 68

def each; 1.upto(size){ |i| yield page(i) }; end

#offset(page) ⇒ Object

get the offset property about the page. it is simply (page-1)*@per_page



87
88
89
# File 'lib/ludy/paginator.rb', line 87

def offset page
  (page-1)*@per_page
end

#page(page) ⇒ Object Also known as: []

create page instance by page number. if page number you specified was not existed, nil would be returned. note, page start at 1, not zero.



75
76
77
78
79
# File 'lib/ludy/paginator.rb', line 75

def page page
  offset = (page-1)*@per_page
  return nil unless page > 0 and offset < count
  Page.new self, page
end

#sizeObject

return the amount of pages



81
# File 'lib/ludy/paginator.rb', line 81

def size; (count/@per_page.to_f).ceil; end

#to_aObject Also known as: pages

return all pages in an array



70
# File 'lib/ludy/paginator.rb', line 70

def to_a; map{|e|e}; end