Rails tip #5: Atom param parser

The Atom Publishing Protocol is wonderfully RESTful, so it's a natural fit for a Rails application.

One thing you'll run into, though, is that AtomPub posts application/atom+xml data rather than the usual application/x-www-form-urlencoded stuff, so you'll have to write some extra code to handle it.

The good news is that ActionController::Base helps you out. Instead of having to branch on the request type and fatten your controller, you can register a custom param_parser.

So, we wrote Hash.from_atom to transform the incoming xml into the usual { :entry => { ... } } params. Then, we registered it in an initializer:

ActionController::Base.param_parsers[Mime::ATOM] = lambda do |body|
  Hash.from_atom(body)
end

And our controller can now handle either regular form postings or AtomPub entries with the same line of code:

class EntriesController < ApplicationController
  def create
    @entry = @collection.entries.build(params[:entry])
    # ...
  end
end

Not bad.

5 Rails tips

Each day this week, Joachim and I will post something we've learned in our time programming together. It's fun to do, and we might just win something as well.

So far, we've written:

  1. Reloadable custom FormBuilder
  2. Faking DATA in tests
  3. Filter BLOBs from ActiveRecord logging
  4. Writing Capistrano recipes to be loaded from gems
  5. Atom param parser