planetscale / fast_page

Blazing fast pagination for ActiveRecord with deferred joins ⚡️

Home Page:https://planetscale.com/blog/fastpage-faster-offset-pagination-for-rails-apps

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Usage with api-pagination and pagy

slhck opened this issue · comments

This is more of a question about the usage of this Gem.

I am using api-pagination in combination with pagy to provide a paginated API.
This might be as simple as the example shown here.

Internally api-pagination calls pagy via Pagy.new; here you can also see the offset and limit being applied.

How would I make this work with fast_page?

When I add the method from the README to my controller, it is not being called.

For now I was able to monkey-patch my way out of this issue by simply adding this to the controller:

module ApiPagination
  class << self
    def paginate_with_pagy(collection, options)
      if Pagy::DEFAULT[:max_per_page] && options[:per_page] > Pagy::DEFAULT[:max_per_page]
        options[:per_page] = Pagy::DEFAULT[:max_per_page]
      elsif options[:per_page] <= 0
        options[:per_page] = Pagy::DEFAULT[:items]
      end

      pagy = pagy_from(collection, options)
      collection = if collection.respond_to?(:offset) && collection.respond_to?(:limit)
        collection.offset(pagy.offset).limit(pagy.items).fast_page
      else
        collection[pagy.offset, pagy.items]
      end

      return [collection, pagy]
    end
  end
end

Notice the addition lf .fast_page in one of the lines.

But there is probably a cleaner way to do this…

Thanks @slhck! I'm going to look at this more when I have a chance.

I'm expecting your way of overriding the method is probably best. Also possible pagy may have changed since I last used it with fast_page.

I'll see if I can find a nicer way, if not, will update the readme.