Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,12 +308,14 @@ use the `jsonapi_pagination_meta` method:

```

If you want to change the default number of items per page, use the
If you want to change the default number of items per page or define a custom logic to handle page size, use the
`jsonapi_page_size` method:

```ruby
def jsonapi_page_size
30
def jsonapi_page_size(pagination_params)
per_page = pagination_params[:size].to_f.to_i
per_page = 30 if per_page > 30
per_page
end
```
### Deserialization
Expand Down
17 changes: 13 additions & 4 deletions lib/jsonapi/pagination.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,27 @@ def jsonapi_pagination_meta(resources)
# @return [Array] with the offset, limit and the current page number
def jsonapi_pagination_params
pagination = params[:page].try(:slice, :number, :size) || {}
per_page = pagination[:size].to_f.to_i
per_page = jsonapi_page_size if per_page < 1
per_page = jsonapi_page_size(pagination)
num = [1, pagination[:number].to_f.to_i].max

[(num - 1) * per_page, per_page, num]
end

# Retrieves the default page size
#
# @param per_page_param [Hash] opts the paginations params
# @option opts [String] :number the page number requested
# @option opts [String] :size the page size requested
#
# @return [Integer]
def jsonapi_page_size
self.class.const_get(:JSONAPI_PAGE_SIZE).to_i
def jsonapi_page_size(pagination_params)
per_page = pagination_params[:size].to_f.to_i

return self.class
.const_get(:JSONAPI_PAGE_SIZE)
.to_i if per_page < 1

per_page
end

# Fallback to Rack's parsed query string when Rails is not available
Expand Down