Last active
August 1, 2024 08:35
-
-
Save turadg/5570181 to your computer and use it in GitHub Desktop.
Handle only 404s dynamically. It uses a normal controller and route for 404s, letting everything else go to the Rails default /public error pages. In my case it was to use the subdomain logic in my ApplicationController.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MyApp | |
class Application < Rails::Application | |
require Rails.root + 'lib/custom_public_exceptions' | |
config.exceptions_app = CustomPublicExceptions.new Rails.public_path | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomPublicExceptions < ActionDispatch::PublicExceptions | |
def call(env) | |
status = env["PATH_INFO"][1..-1] | |
if "404" == status | |
# handle just 404 in our routes | |
MyApp::Application.routes.call env | |
else | |
super env | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ErrorsController < ApplicationController | |
skip_before_filter :authenticate_user! # if using Devise | |
def not_found | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Geknowm::Application.routes.draw do | |
match "/404", :to => "errors#not_found" | |
end |
@henrik Was that intentional? xD
@henrick I hope that link to a nginx 404 was in fact intentional got a good chuckle from that.
lol you guys are too meta.
Pretty great, one simple change is to use Rails.application.routes.call env
instead of MyApp::Application.routes.call env
so that you don't have to change that line to your application
class CustomPublicExceptions < ActionDispatch::PublicExceptions
def call(env)
status = env["PATH_INFO"][1..-1]
if "404" == status
# handle just 404 in our routes
MyApp::Application.routes.call env
else
super env
end
end
end
Can you write spec for this?
how, if I want to call the page can not be found on another controller to provide the conditions?
if no_session.nil?
# how to call 404 page
return false
else
return true
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wrote up my modifications as a blog post: http://thepugautomatic.com/2014/08/custom-404-page-with-rails-4/