summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAzul <azul@riseup.net>2016-08-17 16:11:46 +0200
committerAzul <azul@riseup.net>2016-08-17 16:12:17 +0200
commit20bb76848b852bba9ab3c99b1c2a68464585bd56 (patch)
treebbcd028b74179ea7c76abb1ffb66a5f52acd881b
parent44910c0909f28791fe6725fa76301e5111ece3b4 (diff)
bugfix: send 406 if an unexpected format is asked for
It used to run the action and then trigger a 500 because the template was not found. fixes !3 .
-rw-r--r--app/controllers/application_controller.rb19
-rw-r--r--test/functional/home_controller_test.rb16
2 files changed, 35 insertions, 0 deletions
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 2af2f29..61ced21 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,5 +1,6 @@
class ApplicationController < ActionController::Base
protect_from_forgery
+ before_action :check_mime_types
before_filter :set_locale
before_filter :no_cache_header
before_filter :no_frame_header
@@ -9,8 +10,26 @@ class ApplicationController < ActionController::Base
ActiveSupport.run_load_hooks(:application_controller, self)
+ # by default we only respond to html.
+ # If you want to respond with json you are probably working on
+ # an ApiController.
+ respond_to :html
+
protected
+ # UPGRADE: this won't be needed in Rails 5 anymore as it's the default
+ # behavior if a template is present but a different format would be
+ # rendered and that template is not present
+ def check_mime_types
+ mimes = collect_mimes_from_class_level()
+ return if mimes.empty?
+
+ collector = ActionController::MimeResponds::Collector.new(mimes, request.variant)
+ unless collector.negotiate_format(request)
+ raise ActionController::UnknownFormat
+ end
+ end
+
def default_error_handler(exc)
respond_to do |format|
format.json { render_json_error(exc) }
diff --git a/test/functional/home_controller_test.rb b/test/functional/home_controller_test.rb
new file mode 100644
index 0000000..cafaac5
--- /dev/null
+++ b/test/functional/home_controller_test.rb
@@ -0,0 +1,16 @@
+require 'test_helper'
+
+class HomeControllerTest < ActionController::TestCase
+
+ def test_renders_okay
+ get :index
+ assert_response :success
+ end
+
+ def test_other_formats_trigger_406
+ assert_raises ActionController::UnknownFormat do
+ get :index, format: :xml
+ end
+ end
+
+end