Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
only try to display an api template in responders if the request is a…
… get or there are no errors

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information
joshk authored and josevalim committed Mar 31, 2011
1 parent 9766997 commit 48404a7
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
13 changes: 9 additions & 4 deletions actionpack/lib/action_controller/metal/responder.rb
Expand Up @@ -131,7 +131,11 @@ def to_html
# responds to :to_format and display it.
#
def to_format
default_render
if get? || !has_errors?
default_render
else
display_errors
end
rescue ActionView::MissingTemplate => e
api_behavior(e)
end
Expand All @@ -155,9 +159,6 @@ def api_behavior(error)

if get?
display resource
elsif has_errors?
# bypass the options merging of display
controller.render format => resource.errors, :status => :unprocessable_entity
elsif post?
display resource, :status => :created, :location => api_location
elsif has_empty_resource_definition?
Expand Down Expand Up @@ -210,6 +211,10 @@ def display(resource, given_options={})
controller.render given_options.merge!(options).merge!(format => resource)
end

def display_errors
controller.render format => resource.errors, :status => :unprocessable_entity
end

# Check whether the resource has errors.
#
def has_errors?
Expand Down
21 changes: 21 additions & 0 deletions actionpack/test/controller/mime_responds_test.rb
Expand Up @@ -558,6 +558,10 @@ def using_resource_with_status_and_location
respond_with(resource, :location => "http://test.host/", :status => :created)
end

def using_invalid_resource_with_template
respond_with(resource)
end

def using_resource_with_responder
responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" }
respond_with(resource, :responder => responder)
Expand Down Expand Up @@ -970,6 +974,23 @@ def test_using_resource_with_status_and_location_with_invalid_resource
assert_equal nil, @response.location
end

def test_using_invalid_resource_with_template
errors = { :name => :invalid }
Customer.any_instance.stubs(:errors).returns(errors)

@request.accept = "text/xml"

post :using_invalid_resource_with_template
assert_equal errors.to_xml, @response.body
assert_equal 422, @response.status
assert_equal nil, @response.location

put :using_invalid_resource_with_template
assert_equal errors.to_xml, @response.body
assert_equal 422, @response.status
assert_equal nil, @response.location
end

def test_using_resource_with_responder
get :using_resource_with_responder
assert_equal "Resource name is david", @response.body
Expand Down
@@ -0,0 +1 @@
<content>I should not be displayed</content>

0 comments on commit 48404a7

Please sign in to comment.