Adding Pagination to Twitter API Calls with will_paginate
First of all, if you're not using will_paginate for all of your pagination then you should be. It's well known that the built in pagination in Rails is slow and clunky. will_paginate will easily replace your ActiveRecord pagination, but it can paginate just about anything else.
John Nunemaker's Twitter Plugin makes short work of hooking your app up to the Twitter API. With a few strokes of code you can be pulling statuses down like mad. Now if you want to list a bunch of statuses you'll likely want to have some kind of pagination.
First there's the standard Auth
httpauth = Twitter::HTTPAuth.new(username, password)
client = Twitter::Base.new(httpauth)
Then setup some pagination defaults, and grab some tweets.
current_page = params[:page] || 1
per_page = 100
tweets = client.user_timeline(:count => per_page, :page => current_page)
Then just wrap the paginator around your collection and the deed is done.
if !tweets.empty?
@tweets = WillPaginate::Collection.create(current_page, per_page, tweets.first.user.statuses_count) do |pager|
pager.replace(tweets)
end
end
Finally, insert the pagination links in the view.
<%= will_paginate @tweets %>
That's it. A marriage of two great plugins indeed.


Post a Comment