Sha256: 92087800375e2b64cccced081d6a1295ae6df7f12a1a4f2b060e85fe0cba168d

Contents?: true

Size: 1.22 KB

Versions: 2

Compression:

Stored size: 1.22 KB

Contents

# See Pagy::Backend API documentation: https://ddnexus.github.io/pagy/api/backend
# frozen_string_literal: true

class Pagy
  # Define a few generic methods to paginate an ORM collection out of the box,
  # or any collection by overriding pagy_get_items and/or pagy_get_vars in your controller
  # See also the extras if you need specialized methods to paginate Arrays or other collections
  module Backend
    private

    # Return Pagy object and items
    def pagy(collection, vars = {})
      pagy = Pagy.new(pagy_get_vars(collection, vars))
      [pagy, pagy_get_items(collection, pagy)]
    end

    # Sub-method called only by #pagy: here for easy customization of variables by overriding
    def pagy_get_vars(collection, vars)
      pagy_set_items_from_params(vars) if defined?(ItemsExtra)
      vars[:count] ||= (c = collection.count(:all)).is_a?(Hash) ? c.size : c
      vars[:page]  ||= params[vars[:page_param] || DEFAULT[:page_param]]
      vars
    end

    # Sub-method called only by #pagy: here for easy customization of record-extraction by overriding
    def pagy_get_items(collection, pagy)
      # This should work with ActiveRecord, Sequel, Mongoid...
      collection.offset(pagy.offset).limit(pagy.items)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pagy-5.0.1 lib/pagy/backend.rb
pagy-5.0.0 lib/pagy/backend.rb