diff --git a/README.md b/README.md index fe94452..5e86183 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/jsonapi/pagination.rb b/lib/jsonapi/pagination.rb index 03ae22d..a98d149 100644 --- a/lib/jsonapi/pagination.rb +++ b/lib/jsonapi/pagination.rb @@ -96,8 +96,7 @@ 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] @@ -105,9 +104,19 @@ def jsonapi_pagination_params # 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