Skip to content

Commit 7cd3698

Browse files
authored
always call jsonapi_page_size method on pagination enabled requests (#40)
* always call jsonapi_page_size method on pagination enabled requests pass the per_page_param to the jsonapi_page_size method * pass pagination to jsonapi_page_size and handle string-to-int conversion in jsonapi_page_size * update readme to reflect changes * fix woring
1 parent e62c5c3 commit 7cd3698

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

README.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -308,12 +308,14 @@ use the `jsonapi_pagination_meta` method:
308308

309309
```
310310

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

314314
```ruby
315-
def jsonapi_page_size
316-
30
315+
def jsonapi_page_size(pagination_params)
316+
per_page = pagination_params[:size].to_f.to_i
317+
per_page = 30 if per_page > 30
318+
per_page
317319
end
318320
```
319321
### Deserialization

lib/jsonapi/pagination.rb

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,18 +96,27 @@ def jsonapi_pagination_meta(resources)
9696
# @return [Array] with the offset, limit and the current page number
9797
def jsonapi_pagination_params
9898
pagination = params[:page].try(:slice, :number, :size) || {}
99-
per_page = pagination[:size].to_f.to_i
100-
per_page = jsonapi_page_size if per_page < 1
99+
per_page = jsonapi_page_size(pagination)
101100
num = [1, pagination[:number].to_f.to_i].max
102101

103102
[(num - 1) * per_page, per_page, num]
104103
end
105104

106105
# Retrieves the default page size
107106
#
107+
# @param per_page_param [Hash] opts the paginations params
108+
# @option opts [String] :number the page number requested
109+
# @option opts [String] :size the page size requested
110+
#
108111
# @return [Integer]
109-
def jsonapi_page_size
110-
self.class.const_get(:JSONAPI_PAGE_SIZE).to_i
112+
def jsonapi_page_size(pagination_params)
113+
per_page = pagination_params[:size].to_f.to_i
114+
115+
return self.class
116+
.const_get(:JSONAPI_PAGE_SIZE)
117+
.to_i if per_page < 1
118+
119+
per_page
111120
end
112121

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

0 commit comments

Comments
 (0)