This is a single archived entry from Stefan Tilkov’s blog. For more up-to-date content, check out my author page at INNOQ, which has more information about me and also contains a list of published talks, podcasts, and articles. Or you can check out the full archive.

Paging XML with will_paginate for Rails

Stefan Tilkov,

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 => 'http://www.w3.org/2005/Atom', 'xml:base' => base_uri, 'xml:lang' => 'en-us' do
xml.link :rel => 'self', :type => 'application/atom+xml', :href => request.url
xml.link :rel => 'alternate', :type => 'text/html', :href => orders_url
will_paginate(@orders, :xml => true, :builder => xml)
xml.id orders_url
xml.title 'Feed for OM order updates'
xml.updated Order.maximum(:updated_at).iso8601
for order in @orders do
... # render entries
end
end

This will render something like this:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-us" xml:base="http://om.example.com/">
<link type="application/atom+xml" rel="self" href="http://om.example.com/orders.atom?page=2"/>
<link type="text/html" rel="alternate" href="http://om.example.com/orders"/>
<link rel="next" href="/orders.atom?page=3"/>
<link rel="prev" href="/orders.atom?page=1"/>
<id>http://om.example.com/orders</id>
<title>Feed for OM order updates</title>
<updated>2009-04-07T07:44:56Z</updated>

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, stephan.schloepke.de 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.