Sha256: 0c9bac43dbec9b7e6fe1a0bd5f9b0c11ee3bae9f1e45f91f6bc6b85291a66956

Contents?: true

Size: 1.31 KB

Versions: 41

Compression:

Stored size: 1.31 KB

Contents

module Locomotive::Steam
  module Models

    class Pager

      DEFAULT_PER_PAGE = 10.freeze

      attr_reader :collection, :current_page, :per_page, :total_pages, :total_entries

      def initialize(source, page, per_page)
        @current_page, @per_page = page || 1, per_page || DEFAULT_PER_PAGE

        @total_entries  = source.count
        @total_pages    = (@total_entries.to_f / @per_page).ceil

        index   = (@current_page - 1) * @per_page
        offset  = (index + @per_page - 1) >= @total_entries ? @total_entries : (index + @per_page - 1)

        @collection = paginate(source, index, offset)
      end

      def previous_page
        current_page <= 1 ? nil : current_page - 1
      end

      def next_page
        current_page >= total_pages ? nil : current_page + 1
      end

      def to_liquid
        {
          collection:       collection,
          current_page:     current_page,
          per_page:         per_page,
          previous_page:    previous_page,
          next_page:        next_page,
          total_entries:    total_entries,
          total_pages:      total_pages
        }
      end

      private

      def paginate(source, index, offset)
        limit = offset - index + 1
        limit = 0 if limit < 1
        source.send(:slice, index, limit) || []
      end

    end

  end
end

Version data entries

41 entries across 41 versions & 1 rubygems

Version Path
locomotivecms_steam-1.5.0.rc0 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.5.0.beta3 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.5.0.beta2 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.5.0.beta1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.4.1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.4.0 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.4.0.rc2 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.4.0.rc1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.4.0.pre.rc.1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.3.0 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.3.0.rc2 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.1.2 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.2.1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.3.0.rc1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.2.0 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.2.0.rc3 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.2.0.rc2 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.2.0.rc1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.2.0.beta1 lib/locomotive/steam/models/pager.rb
locomotivecms_steam-1.1.1 lib/locomotive/steam/models/pager.rb