Sha256: 5b19b68928da0152ea410030b477eddb6e004f2be8f65daad2ff28298abb93fd

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

require 'pagy'

class Pagy

  class Countless < Pagy

    # Merge and validate the options, do some simple arithmetic and set a few instance variables
    def initialize(vars={})
      @vars ||= VARS.merge(vars.delete_if{|_,v| v.nil? || v == '' })    # default vars + cleaned vars (can be overridden)
      { items:1, outset:0, page:1 }.each do |k,min|                     # validate instance variables
        (@vars[k] && instance_variable_set(:"@#{k}", @vars[k].to_i) >= min) \
         or raise(ArgumentError, "expected :#{k} >= #{min}; got #{@vars[k].inspect}")
      end
      @offset = @items * (@page - 1) + @outset                          # pagination offset + outset (initial offset)
    end

    # Finalize the instance variables based on the retrieved items
    def finalize(items)
      items == 0 && @page > 1 and raise(OverflowError.new(self), "page #{@page} got no items")
      @pages = @last = (items > @items ? @page + 1 : @page)             # set the @pages and @last
      @items = items if items < @items && items > 0                     # adjust items for last non-empty page
      @from  = items == 0 ? 0 : @offset+1 - @outset                     # page begins from item
      @to    = items == 0 ? 0 : @offset + @items - @outset              # page ends to item
      @prev  = (@page-1 unless @page == 1)                              # nil if no prev page
      @next  = (@page+1 unless @page == @last)                          # nil if no next page
      self
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pagy-1.1.0 lib/pagy/countless.rb