#2798, respond_with ... location: nil requirement, and returning status, location, and wrapping errors automatically for controllers providing JSON, XML, etc. services

Regarding: https://github.com/rails/rails/issues/2798

Before when I was using respond_to, I didn’t have to specify :location, but after switching to respond_with, I do, so I ran into that issue. From what I’ve read, location is only supposed to be required for a RESTful service specifically when :status is :created (with the location where you can go to get the resource) or :accepted (when further processing is needed on the request and I guess you are giving the location of where they can do to wait on it and eventually get it from that url). I understand that it may not be backwards compatible, but is there a way to not have to have it to be set to nil explicitly if it is unnecessary? From that bug, it looked like that would be a breaking change, so I’m wondering if something new should be considered for Rails 4?

How about something like (sorry for my bad function names- having trouble coming up with anything good):

wrap do

Something that may call save/setup transaction, etc. goes here.

By wrapping this in a block the wrap method that yields this block could

do a begin … rescue around the yield and if StandardError rescued

it could set status :internal_server_error and return a generic json response

containing the error.

@my_model.save

respond would be similar to respond_with/respond_to but is able

to look at @my_model.errors to determine if there are validation errors

in which case it would return :unprocessable_entity with the errors wrapped

in JSON for json format, etc., otherwise it would look at the request to

determine the operation type or you could pass :create, :destroy, :update,

etc. as an argument. Based on operation type would set status :created if in create,

head :no_content if destroy, status :ok if in update, show, index. And you

would specify status: :accepted if it is an async request. Would set the

location based on controller and action in request or use a specified location.

respond @my_model end

A really bad idea or not? I could write a gem for it easily if it were just a matter of adding a wrapping method and convenience response method that could call respond_with/respond_to.

Thanks!

Just implemented so you could see what I mean, but didn’t test, so no idea if it works: https://github.com/garysweaver/convenient-actionpack

Ok, not good. Was confused about stuff that respond_with says it is already doing, at least in master/Rails 4. Looking at mime_responds.rb, etc. in metal now. Sorry about that. I think something like the wrap or having a standard method to call to respond with a StandardError would be good and not having to specify a nil location.