metaduck
31Mar/102

How to paginate outside of the database with will_paginate

will_paginate is a great plugin. I have been using it since I started on Rails.

If you want to paginate records that are inside your database it works great.

But what if you want to paginate records that come from, say an external webservice?

Well, you can use the WillPaginate::Collection class.

This class will let you mimic the collection that will work on a pager, so you can use the view helper pager seamlessly throughout your app.

Just use it like this:

@entries = WillPaginate::Collection.create(1, 10) do |pager|
  result = Webservice.get(...) # get your results
  # inject the result array into the paginated collection:
  pager.replace(result)

  unless pager.total_entries
    # the pager didn't manage to guess the total count, do it manually
    pager.total_entries = result.count
  end
end

About Pedro Teixeira

Pedro Teixeira is a former Enterprise Java Beans technical project manager for Clarity Europe (BES Tech Ventures). On 2004 he founded a services company ( http://berro.pt ), focused on the tourism industry throughout 2005-2008, briefly worked for http://www.expedita.com, shifted to product development on 2007, rebuilt http://netmadeira.com on 2009 for ZON Madeira. On early 2010 he started freelance work for Avallain, an e-Learning company strongly focused on delivering multi-media learning content and learning community expericences.
Filed under: Rails Leave a comment