Using JSON template builders with respond_with

Quick question: what's the best way to use a JSON template builder (jbuilder, etc) with respond_with? The current implementation loses some of the semantics in that situation; for instance, adding a template for the create action means that the response comes back as a "200 OK" instead a "201 Created".

Is there a clean way to handle this? I like the idea of avoiding hackery like including view helpers in models for as_json, but the response code changes mean that I'm back to writing out respond_tos manually.


--Matt Jones

Maybe you can just add options to the respond_with call, as shown in
the documentation [1]: respond_with(@resource, :status => :created)
but this will also return a 201 status code for html responses. I
don’t know if this can be a problem.

Otherwise, you can just rewrite a Responder from scratch, it just
needs to respond to call with three arguments, the controller
instance, and the resource(s) and options passed to respond_with. You
can then set it as the default responder on ApplicationController.

As far as the default Responder is concerned, its algorithm is wrong
in the sense that it will not behave as an API (201 responses and
such) if there’s a template present. I don’t know if it’s possible to
change this without breaking apps out there. Maybe we could build a
better responder next to the old one and leave the choice up to the
user to use it.


ActiveModel::Serializers does this pretty nicely. You could take a look at it.