简体   繁体   中英

ActiveResource pagination

What would be the best way to approach pagination over an API with active resource? I'm building the API and the app consuming the API so I need both ends of the equation.

I've seen people setting headers for what page they want in ActiveResource (X-PERPAGE for example).

Any suggestions would be great. Looking for best solution.

ActiveResource 4.0.0.beta1 introduces ActiveResource::Collection , which (according to the documentation in the source code) is a wrapper to handle parsing index responses . A Post class can be set up to handle it with:

class Post < ActiveResource::Base
  self.site = "http://example.com"
  self.collection_parser = PaginatedCollection
end

You can embed your pagination data inside your API response and retrieve them with ActiveResource::Collection .

See a detailed explanation on how to use this: http://javiersaldana.com/2013/04/29/pagination-with-activeresource.html

1) patch activeresource with next code

module ActiveResource
  class Connection
    alias_method :origin_handle_response, :handle_response 
    def handle_response(response)
      Thread.current["active_resource_response_#{self.object_id}"]  = response
      origin_handle_response(response)
    end  

    def response
      Thread.current["active_resource_response_#{self.object_id}"] 
    end   
  end
end 

it will add possibility to read response after rest method was executed 2) on server side with kaminari you can do next

@users = User.page(params[:page]).per(params[:per_page])
response.headers["total"] = @users.total_count.to_s
response.headers["offset"] = @users.offset_value.to_s
response.headers["limit"] = @users.limit_value.to_s
respond_with(@users)

3) on client side again with kaminari

users = Users.all(:params=>params)
response = Users.connection.response
@users = Kaminari::PaginatableArray.new(
    users,
    {
      :limit => response['limit'].to_i ,
      :offset =>response['offset'].to_i ,
      :total_count => response['total'].to_i
    }   
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM