Skip to content

Instantly share code, notes, and snippets.

@leshill
Created August 10, 2011 18:29
Show Gist options
  • Save leshill/1137711 to your computer and use it in GitHub Desktop.
Save leshill/1137711 to your computer and use it in GitHub Desktop.
Responding to a JSON PUT with either a 200 and the updated JSON or 204 and no body
# The default Responder returns 200, {} for a PUT success.
# Not really happy with that. A 204, nil would be better.
# However, for most resources the result of a PUT is that something changes (updated_at).
# A 200 with the updated resource makes sense in that case.
#
# Not really happy with this first cut.
#
class ResourceResponder < ActionController::Responder
protected
def api_behavior(error)
raise error unless resourceful?
if get?
display resource
elsif has_errors?
display resource.errors, :status => :unprocessable_entity
elsif post?
display resource, :status => :created, :location => api_location
elsif put?
# Simple PUTs end up with a has_changes? being true, not sure that is always the desired behavior
if has_changes?
display resource, :status => :ok, :location => api_location
else
display head(:no_content)
end
# Or for no response back, the correct status is
# display head(:no_content)
elsif has_empty_resource_definition?
display empty_resource, :status => :ok
else
display head(:ok)
end
end
def has_changes?
resource.respond_to?(:previous_changes) && resource.previous_changes.any?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment