Module: Pagy::GearboxExtra

Included in:
Pagy
Defined in:
lib/pagy/extras/gearbox.rb

Overview

Automatically change the number of items per page depending on the page number accepts an array as the :gearbox_items variable, that will determine the items for the first pages

Instance Method Summary collapse

Instance Method Details

#setup_items_varObject

Setup @items based on the :gearbox_items variable

Raises:



12
13
14
15
16
17
18
19
20
# File 'lib/pagy/extras/gearbox.rb', line 12

def setup_items_var
  return super if !@vars[:gearbox_extra] || @vars[:items_extra]

  gears = @vars[:gearbox_items]
  raise VariableError.new(self, :gearbox_items, 'to be an Array of positives', gears) \
        unless gears.is_a?(Array) && gears.all? { |num| num.positive? rescue false } # rubocop:disable Style/RescueModifier

  @items = gears[@page - 1] || gears.last
end

#setup_last_varObject

Setup Pagy @last based on the :gearbox_items variable and @count



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pagy/extras/gearbox.rb', line 23

def setup_last_var
  return super if !@vars[:gearbox_extra] || @vars[:items_extra]

  gears = @vars[:gearbox_items]
  # This algorithm is thousands of times faster than the one in the geared_pagination gem
  @last = (if count > (sum = gears.sum)
             [((count - sum).to_f / gears.last).ceil, 1].max + gears.count
           else
             pages     = 0
             remainder = count
             while remainder.positive?
               pages     += 1
               remainder -= gears[pages - 1]
             end
             [pages, 1].max
           end)
  @last = vars[:max_pages] if vars[:max_pages] && @last > vars[:max_pages]
end

#setup_offset_varObject

Setup @offset based on the :gearbox_items variable



43
44
45
46
47
48
49
50
51
52
# File 'lib/pagy/extras/gearbox.rb', line 43

def setup_offset_var
  return super if !@vars[:gearbox_extra] || @vars[:items_extra]

  gears   = @vars[:gearbox_items]
  @offset = if @page <= gears.count
              gears[0, @page - 1].sum
            else
              gears.sum + (gears.last * (@page - gears.count - 1))
            end + @outset
end