Skip to content

Commit

Permalink
chained method for extra items overrides
Browse files Browse the repository at this point in the history
  • Loading branch information
ddnexus committed Jul 29, 2018
1 parent 041d31d commit fb48976
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
4 changes: 2 additions & 2 deletions docs/extras/items.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ pagy(scope, items: 30)

## Methods

The `items` extra overrides a couple of builtin methods and adds a helper to the `Pagy::Frontend` module.
The `items` extra overrides a couple of builtin methods and adds a helper to the `Pagy::Frontend` module. All the overridden methods are alias-chained with `*_with_items` and `*_without_items`)

### pagy_get_vars(collection, vars)

This extra overrides the `pagy_get_vars` method of the `Pagy::Backend` module in order to set the `:items` variable, pulled from the request-params. The built-in `pagy_get_vars` method is aliased as `built_in_pagy_get_vars` and it's called internally and still available.
This extra overrides the `pagy_get_vars` method of the `Pagy::Backend` module in order to set the `:items` variable, pulled from the request-params.

### pagy_url_for(page, pagy)

Expand Down
13 changes: 7 additions & 6 deletions lib/pagy/extras/items.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,24 @@ class Pagy
# Handle a custom number of :items from params
module Backend ; private

alias_method :built_in_pagy_get_vars, :pagy_get_vars

def pagy_get_vars(collection, vars)
alias_method :pagy_get_vars_without_items, :pagy_get_vars
def pagy_get_vars_with_items(collection, vars)
vars[:items] ||= (items = params[vars[:items_param] || VARS[:items_param]]) && # :items from :items_param
[items&.to_i, vars.key?(:max_items) ? vars[:max_items] : VARS[:max_items]].compact.min # :items capped to :max_items
built_in_pagy_get_vars(collection, vars)
pagy_get_vars_without_items(collection, vars)
end
alias_method :pagy_get_vars, :pagy_get_vars_with_items

end

module Frontend

# This works with all Rack-based frameworks (Sinatra, Padrino, Rails, ...)
def pagy_url_for(page, pagy)
alias_method :pagy_url_for_without_items, :pagy_url_for
def pagy_url_for_with_items(page, pagy)
p_vars = pagy.vars; params = request.GET.merge(p_vars[:page_param] => page, p_vars[:items_param] => p_vars[:items]).merge!(p_vars[:params])
"#{request.path}?#{Rack::Utils.build_nested_query(pagy_get_params(params))}#{p_vars[:anchor]}"
end
alias_method :pagy_url_for, :pagy_url_for_with_items

# Return the items selector HTML. For example "Show [20] items per page"
def pagy_items_selector(pagy, id=caller(1,1)[0].hash)
Expand Down

0 comments on commit fb48976

Please sign in to comment.