Paging XML with will_paginate for Rails

, May 22, 2009

I needed to paginate an Atom feed, and didn’t want to build it myself (specifically because I’m rendering the same content as HTML, anyway). So this fork adds pagination support for XML, usable in Atom feeds or other XML resource representations.

Usage example:

xml.instruct! :xml, :encoding => "UTF-8"
xml.feed :xmlns => '', 'xml:base' => base_uri, 'xml:lang' => 'en-us' do :rel => 'self', :type => 'application/atom+xml', :href => request.url :rel => 'alternate', :type => 'text/html', :href => orders_url
will_paginate(@orders, :xml => true, :builder => xml) orders_url
xml.title 'Feed for OM order updates'
xml.updated Order.maximum(:updated_at).iso8601
for order in @orders do
... # render entries

This will render something like this:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="" xml:lang="en-us" xml:base="">
<link type="application/atom+xml" rel="self" href=""/>
<link type="text/html" rel="alternate" href=""/>
<link rel="next" href="/orders.atom?page=3"/>
<link rel="prev" href="/orders.atom?page=1"/>
<title>Feed for OM order updates</title>

In other words, use will_paginate as you would use it in HTML (the controller code can stay unchanged), and add the :xml => true option. This will make will_paginate return an XML string representation containing appropriate elements. Alternatively, you can pass in an XML builder and it will use that instead.

Works with Rails 2.3.2.

Note that my experience with git and GitHub is limited, I’m happy about suggestions on how to make this more useful. I’m also entirely satisfied if there’s a better solution and someone points me to it.

On May 22, 2009 7:33 PM, said:

I would also add the FIRST and LAST link relation if possible (first usually should always be possible) since RFC5005 recommends that you should have as many as practical and applicable of the four link relations.

On May 22, 2009 8:36 PM, Stefan Tilkov said:

Good point. I’ve updated the code; it now supports a “:first” and “:last” option that when set to true will make the pagination generate the first and last relations.