Skip to content

Commit

Permalink
Allow decorating objects after pagination (#91)
Browse files Browse the repository at this point in the history
* Rubocop fix: Use filter_map instead of map { ... }.compact

Currently, builds are failing because of Rubocop complaining about these
three lines.

* Fix specs with Ransack 4.0

Ransack 4 requires explicitly allowlisting ransackable attributes and
associations for each model. This causes the specs to fail with the most
recent Ransack version. This fixes those spec failures.

* Allow decorating objects after pagination

This simplification allows decorating objects after they are paginated,
without losing the correct total object count.

I'm using an instance variable on the including controller here, because
the decorating the paginated collection will have us lose the instance
variable we set on it.

Here's the case where this happens: We have a complex ActiveRecord
collection that we run through Ransack and Kaminari, but before
rendering we want to convert each object in it using a
`SimpleDelegator`.

Here's a simplified version of the controller action we're looking at:

```
  class UserDecorator < SimpleDelegator
    def fantastic_for_rendering
      "Whoah"
    end
  end

  def index
    allowed_fields = [
      :first_name, :last_name, :created_at,
      :notes_created_at, :notes_quantity
    ]
    options = { sort_with_expressions: true }

    jsonapi_filter(User.all, allowed_fields, options) do |filtered|
      result = filtered.result
      jsonapi_paginate(result) do |paginated|
        paginated = paginated.map { |user| UserDecorator.new() }
        render jsonapi: paginated
      end
    end
  end
```

---------

Co-authored-by: Stas <[email protected]>
  • Loading branch information
mamhoff and stas authored Jun 23, 2024
1 parent 52b4128 commit 5f52cdd
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
15 changes: 4 additions & 11 deletions lib/jsonapi/pagination.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ module Pagination
def jsonapi_paginate(resources)
offset, limit, _ = jsonapi_pagination_params

# Cache the original resources size to be used for pagination meta
@_jsonapi_original_size = resources.size

if resources.respond_to?(:offset)
resources = resources.offset(offset).limit(limit)
else
original_size = resources.size
resources = resources[(offset)..(offset + limit - 1)] || []

# Cache the original resources size to be used for pagination meta
resources.instance_variable_set(:@original_size, original_size)
end

block_given? ? yield(resources) : resources
Expand Down Expand Up @@ -64,13 +63,7 @@ def jsonapi_pagination_meta(resources)

numbers = { current: page }

if resources.respond_to?(:unscope)
total = resources.unscope(:limit, :offset, :order).size
else
# Try to fetch the cached size first
total = resources.instance_variable_get(:@original_size)
total ||= resources.size
end
total = @_jsonapi_original_size

last_page = [1, (total.to_f / limit).ceil].max

Expand Down
1 change: 1 addition & 0 deletions spec/dummy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def index
result = result.to_a if params[:as_list]

jsonapi_paginate(result) do |paginated|
paginated = paginated.to_a if params[:decorate_after_pagination]
render jsonapi: paginated
end
end
Expand Down
23 changes: 22 additions & 1 deletion spec/pagination_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,13 @@

context 'on page 2 out of 3' do
let(:as_list) { }
let(:decorate_after_pagination) { }
let(:params) do
{
page: { number: 2, size: 1 },
sort: '-created_at',
as_list: as_list
as_list: as_list,
decorate_after_pagination: decorate_after_pagination
}.compact_blank
end

Expand All @@ -80,6 +82,25 @@
end
end

context 'when decorating objects after pagination' do
let(:decorate_after_pagination) { true }

it do
expect(response).to have_http_status(:ok)
expect(response_json['data'].size).to eq(1)
expect(response_json['data'][0]).to have_id(second_user.id.to_s)

expect(response_json['meta']['pagination']).to eq(
'current' => 2,
'first' => 1,
'prev' => 1,
'next' => 3,
'last' => 3,
'records' => 3
)
end
end

it do
expect(response).to have_http_status(:ok)
expect(response_json['data'].size).to eq(1)
Expand Down

0 comments on commit 5f52cdd

Please sign in to comment.