Class: Kwipper::Paginator

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

Defined Under Namespace

Classes: Page

Constant Summary collapse

PAGE_PARAM_NAME =
'page'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, page: 1, per: 20, path: '') ⇒ Paginator

Returns a new instance of Paginator.



8
9
10
11
12
13
14
15
# File 'lib/kwipper/paginator.rb', line 8

def initialize(model_class, page: 1, per: 20, path: '')
  @model_class, @path = model_class, path
  @page  = [page.to_i, 1].max
  @per   = [per.to_i, 1].max
  @count = @model_class.count
  @from  = calc_offset + 1
  @to    = [calc_offset + @per, @count].min
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



6
7
8
# File 'lib/kwipper/paginator.rb', line 6

def count
  @count
end

#fromObject (readonly)

Returns the value of attribute from.



6
7
8
# File 'lib/kwipper/paginator.rb', line 6

def from
  @from
end

#toObject (readonly)

Returns the value of attribute to.



6
7
8
# File 'lib/kwipper/paginator.rb', line 6

def to
  @to
end

Instance Method Details

#current_pageObject



50
51
52
# File 'lib/kwipper/paginator.rb', line 50

def current_page
  pages[@page - 1]
end

#get(statement) ⇒ Object



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

def get(statement)
  @model_class.all "#{statement} LIMIT #{@per} OFFSET #{calc_offset}"
end

#next_page_pathObject



44
45
46
47
48
# File 'lib/kwipper/paginator.rb', line 44

def next_page_path
  next_page = current_page.num
  next_page = [next_page, pages.size - 1].min
  pages[next_page].path
end

#on_first_page?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/kwipper/paginator.rb', line 30

def on_first_page?
  @page == 1
end

#on_last_page?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/kwipper/paginator.rb', line 34

def on_last_page?
  pages.last.current?
end

#pagesObject



21
22
23
24
25
26
27
28
# File 'lib/kwipper/paginator.rb', line 21

def pages
  @pages ||= begin
    (0...@count).step(@per).each_with_index.map do |_, num|
      num += 1
      Page.new path_for(num), num, num == @page
    end
  end
end

#prev_page_pathObject



38
39
40
41
42
# File 'lib/kwipper/paginator.rb', line 38

def prev_page_path
  prev_page = current_page.num - 1
  prev_page = [prev_page, 1].max
  pages[prev_page - 1].path
end