Skip to content

Instantly share code, notes, and snippets.

@abriening
Created September 28, 2011 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abriening/1248839 to your computer and use it in GitHub Desktop.
Save abriening/1248839 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :resource_not_found
rescue_from ActionController::RoutingError, :with => :check_request_uri_and_method
rescue_from AbstractController::ActionNotFound, :with => :page_not_found
rescue_from ActionController::MethodNotAllowed, :with => :method_not_allowed
private
def resource_not_found
respond_to do |format|
format.html{ render :template=>'/rescues/record_not_found', :status => 404 }
format.xml{ render :xml => 'Record Not Found', :status => 404 }
format.json{ render :json => 'Record Not Found', :status => 404 }
end
end
def page_not_found
respond_to do |format|
format.html{ render :template=>'/rescues/page_not_found', :status => 404 }
format.xml{ render :xml => 'Page Not Found', :status => 404 }
format.json{ render :json => 'Page Not Found', :status => 404 }
end
end
def method_not_allowed(exception)
response.headers['Allow'] ||= exception.allowed_methods.map { |method_symbol| method_symbol.to_s.upcase } * ', '
respond_to do |format|
format.html{ render :template=>'/rescues/method_not_allowed', :status => 405 }
format.xml{ render :xml => 'Method Not Allowed', :status => 405 }
format.json{ render :json => 'Method Not Allowed', :status => 405 }
end
end
def not_implmented(exception)
response.headers['Allow'] ||= exception.allowed_methods.map { |method_symbol| method_symbol.to_s.upcase } * ', '
respond_to do |format|
format.html{ render :template=>'/rescues/method_not_allowed', :status => 501 }
format.xml{ render :xml => 'Not Implemented', :status => 501 }
format.json{ render :json => 'Not Implemented', :status => 501 }
end
end
def check_request_uri_and_method
method, path = env['REQUEST_METHOD'].downcase.to_sym, env['PATH_INFO']
# Route was not recognized. Try to find out why (maybe wrong verb).
allows = ActionDispatch::HTTP_METHODS.select do |verb|
begin
Rails.application.routes.recognize_path(path, {:method => verb}, false)
rescue ActionController::RoutingError
nil
end
end
if !ActionDispatch::HTTP_METHODS.include?(method)
method_not_allowed ActionController::NotImplemented.new(*allows)
elsif !allows.empty?
method_not_allowed ActionController::MethodNotAllowed.new(*allows)
else
page_not_found
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment