Class: Charming::Components::Paginator

Inherits:
Charming::Component show all
Defined in:
lib/charming/presentation/components/paginator.rb

Overview

Paginator tracks a current page over a collection and renders a compact page indicator: bubbles-style dots ("○ ● ○") or arabic "2/3". Pair it with a List or Table by slicing items through page_items.

Constant Summary collapse

ACTIVE_DOT =
""
INACTIVE_DOT =
""

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Charming::Component

#captures_text?

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(total:, per_page:, page: 0, format: :dots, theme: nil) ⇒ Paginator

total is the collection size, per_page the page size, page the 0-based starting page, and format either :dots (default) or :arabic.



16
17
18
19
20
21
22
# File 'lib/charming/presentation/components/paginator.rb', line 16

def initialize(total:, per_page:, page: 0, format: :dots, theme: nil)
  super(theme: theme)
  @total = [total.to_i, 0].max
  @per_page = [per_page.to_i, 1].max
  @format = format
  @page = page.to_i.clamp(0, page_count - 1)
end

Instance Attribute Details

#pageObject (readonly)

Returns the value of attribute page.



12
13
14
# File 'lib/charming/presentation/components/paginator.rb', line 12

def page
  @page
end

#per_pageObject (readonly)

Returns the value of attribute per_page.



12
13
14
# File 'lib/charming/presentation/components/paginator.rb', line 12

def per_page
  @per_page
end

#totalObject (readonly)

Returns the value of attribute total.



12
13
14
# File 'lib/charming/presentation/components/paginator.rb', line 12

def total
  @total
end

Instance Method Details

#next_pageObject

Advances one page, clamping at the last. Returns self.



35
36
37
38
# File 'lib/charming/presentation/components/paginator.rb', line 35

def next_page
  @page = [page + 1, page_count - 1].min
  self
end

#page_countObject

The number of pages — at least 1, even for an empty collection.



25
26
27
# File 'lib/charming/presentation/components/paginator.rb', line 25

def page_count
  [(total.to_f / per_page).ceil, 1].max
end

#page_items(items) ⇒ Object

The slice of items belonging to the current page.



30
31
32
# File 'lib/charming/presentation/components/paginator.rb', line 30

def page_items(items)
  items[page * per_page, per_page] || []
end

#prev_pageObject

Steps back one page, clamping at the first. Returns self.



41
42
43
44
# File 'lib/charming/presentation/components/paginator.rb', line 41

def prev_page
  @page = [page - 1, 0].max
  self
end

#renderObject

Renders the page indicator in the configured format.



47
48
49
50
51
# File 'lib/charming/presentation/components/paginator.rb', line 47

def render
  return "#{page + 1}/#{page_count}" if @format == :arabic

  Array.new(page_count) { |index| (index == page) ? ACTIVE_DOT : INACTIVE_DOT }.join(" ")
end