Class: Ariadne::PaginationCalculator

Inherits:
Object
  • Object
show all
Defined in:
app/lib/ariadne/pagination_calculator.rb

Overview

Handles pagination calculations and data structure

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(total_count:, page: 1, items_per_page: 10) ⇒ PaginationCalculator

Returns a new instance of PaginationCalculator.



9
10
11
12
13
14
# File 'app/lib/ariadne/pagination_calculator.rb', line 9

def initialize(total_count:, page: 1, items_per_page: 10)
  @total_count = total_count
  @items_per_page = items_per_page
  @pages = calculate_total_pages
  @page = handle_page_overflow(page)
end

Instance Attribute Details

#items_per_pageObject (readonly)

Returns the value of attribute items_per_page.



7
8
9
# File 'app/lib/ariadne/pagination_calculator.rb', line 7

def items_per_page
  @items_per_page
end

#pageObject (readonly)

Returns the value of attribute page.



7
8
9
# File 'app/lib/ariadne/pagination_calculator.rb', line 7

def page
  @page
end

#pagesObject (readonly)

Returns the value of attribute pages.



7
8
9
# File 'app/lib/ariadne/pagination_calculator.rb', line 7

def pages
  @pages
end

#total_countObject (readonly)

Returns the value of attribute total_count.



7
8
9
# File 'app/lib/ariadne/pagination_calculator.rb', line 7

def total_count
  @total_count
end

Instance Method Details

#fromObject



16
17
18
19
20
# File 'app/lib/ariadne/pagination_calculator.rb', line 16

def from
  return 0 if total_count.zero?

  (page - 1) * items_per_page + 1
end

#next_pageObject



28
29
30
# File 'app/lib/ariadne/pagination_calculator.rb', line 28

def next_page
  page < pages ? page + 1 : nil
end

#page_seriesObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/lib/ariadne/pagination_calculator.rb', line 36

def page_series
  return [] if pages <= 1
  return (1..pages).to_a if pages <= 5

  links = []
  links << 1

  if page <= 3
    # Near the beginning: 1 2 3 4 5 6 7 8 ... 20
    (2..8).each { |n| links << n if n <= pages }
    links << nil if pages > 8
    links << pages if pages > 8
  elsif page >= pages - 2
    # Near the end: 1 ... 13 14 15 16 17 18 19 20
    links << nil
    ((pages - 7)..pages).each { |n| links << n if n > 1 }
  else
    # Middle range: 1 ... 9 10 11 12 13 14 ... 20
    links << nil
    ((page - 2)..(page + 2)).each { |n| links << n }
    links << nil
    links << pages
  end

  links
end

#prev_pageObject



32
33
34
# File 'app/lib/ariadne/pagination_calculator.rb', line 32

def prev_page
  page > 1 ? page - 1 : nil
end

#toObject



22
23
24
25
26
# File 'app/lib/ariadne/pagination_calculator.rb', line 22

def to
  return 0 if total_count.zero?

  [page * items_per_page, total_count].min
end