2

It seems like will_paginate and Kaminari are both very tied into ActiveRecord? If the data is obtained through an API, such as

http://www.foo.com/fetch_data?type=products&offset=100&count=20

then how can you use will_paginate or Kaminari to do the pagination? If cannot, is there other pagination solution that can work in this situation?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

3

I already do pagination on a non-AR set for my acts_as_indexed plugin.

In your case it would work something like the following:

def fetch(page=1, per_page=10)
  total_entries = 1000 # Or whatever method you choose to find the total entries.

  returning ::WillPaginate::Collection.new(page, per_page, total_entries) do |pager|
    url = "http://www.foo.com/fetch_data?type=products&offset=#{pager.offset}&count=#{pager.per_page}"

    results = fetch_example(url)# fetch the actual data here.

    pager.replace results
  end
end

Controller:

def index
  @records = fetch(params[:page])
end

Views:

<%= will_paginate @records %>

Fill in your own methods for fetching and processing the data, and working out the total entries.

Douglas F Shearer
  • 25,952
  • 2
  • 48
  • 48
  • You mean then, is not to use any gem at all and just implement everything on your own? hm, implementing the page numbers, how many before, how many after, and if `< 1` or `> page_number_max`, then can't show it, and wanting to show 5 page numbers constantly, these kind of things can be messy. Are there standard helpers or common gem that can do it? – nonopolarity Apr 01 '11 at 13:52
  • Remembered I actually use WillPaginate in a plugin I maintain in a manner that would be useful to you. Have revamped my answer using this method. Allows you to use the nice will_paginate view helpers etc. – Douglas F Shearer Apr 01 '11 at 15:09
0

I wrote my own function to paginate an array of objects. You can modify the code to suit your own needs:

def array_paginate page, per_page, array
  page = page.to_i
  per_page = per_page.to_i
  total_entries = array.count

  total_pages = (total_entries / per_page.to_f).ceil
  data = format_records( array[ (page-1)*per_page..page*per_page-1] )

  {
    page: page,
    total_pages: total_pages,
    data: data,
  }
end
DivinesLight
  • 2,398
  • 2
  • 24
  • 30