Class: Godmin::Paginator

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

Constant Summary collapse

WINDOW_SIZE =
7

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resources, per_page: 25, current_page: nil) ⇒ Paginator

Returns a new instance of Paginator.



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

def initialize(resources, per_page: 25, current_page: nil)
  @resources = resources
  @per_page = per_page
  @current_page = current_page ? current_page.to_i : 1
end

Instance Attribute Details

#current_pageObject (readonly)

Returns the value of attribute current_page.



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

def current_page
  @current_page
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



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

def per_page
  @per_page
end

Instance Method Details

#pagesObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/godmin/paginator.rb', line 17

def pages
  @pages ||= begin
    pages = (1..total_pages).to_a

    return pages unless total_pages > WINDOW_SIZE

    if current_page < WINDOW_SIZE
      pages.slice(0, WINDOW_SIZE)
    elsif current_page > (total_pages - WINDOW_SIZE)
      pages.slice(-WINDOW_SIZE, WINDOW_SIZE)
    else
      pages.slice(pages.index(current_page) - (WINDOW_SIZE / 2), WINDOW_SIZE)
    end
  end
end

#paginateObject



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

def paginate
  @resources.limit(per_page).offset(offset)
end

#total_pagesObject



33
34
35
# File 'lib/godmin/paginator.rb', line 33

def total_pages
  @total_pages ||= (total_resources.to_f / per_page).ceil
end

#total_resourcesObject



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/godmin/paginator.rb', line 37

def total_resources
  @total_resources ||= begin
    count = @resources.count

    if count.respond_to?(:count)
      count.count
    else
      count
    end
  end
end