Skip to content

Instantly share code, notes, and snippets.

@ilyakatz
Last active November 21, 2020 19:27
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilyakatz/6346020 to your computer and use it in GitHub Desktop.
Save ilyakatz/6346020 to your computer and use it in GitHub Desktop.

In order to use asset pipeline available for static error pages (like 404.html), a few steps are required

  • Move static pages from /public into /app/assets

    (eg: public/422.html → app/assets/html/422.html.erb)

  • Add html directory to the asset pipeline

  • Update exceptions middleware to understand assets with digests

# config/application.rb
module MyApp
class Application < Rails::Application
# HTML Assets
config.assets.paths << Rails.root.join('app/assets/html')
config.assets.register_mime_type('text/html', '.html')
config.assets.precompile += %w( .html )
end
end
# config/initializers/exceptions.rb
# http://devoh.com/blog/2012/09/asset-pipeline-error-pages
module ActionDispatch
class PublicAssetExceptions < PublicExceptions
def render_html(status)
found = false
path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
unless path && (found = File.exist?(path))
status_file = "#{status}.html"
asset_status_file = ActionController::Base.helpers.asset_digest_path(status_file)
path = "#{public_path}/#{asset_status_file}"
end
if found || File.exist?(path)
render_format(status, 'text/html', File.read(path))
else
[404, { "X-Cascade" => "pass" }, []]
end
end
end
end
MyApp::Application.configure do
config.middleware.swap(
ActionDispatch::ShowExceptions,
ActionDispatch::ShowExceptions,
ActionDispatch::PublicAssetExceptions.new( #if your sprockets is configured to generate non-digest files
Rails.root.join('public/assets') #it is not necessary to derive from PublicExceptions, you can just use those
)
)
end
#don't forget the tests
feature 'Static Pages' do
scenario 'should show a nice 404 page' do
Rails.application.config.consider_all_requests_local = false
Rails.application.config.action_dispatch.show_exceptions = true
visit "/asdfasf"
page.should have_content("Sorry, that page doesn't exist")
page.driver.status_code.should == 404
end
end
@ilyakatz
Copy link
Author

@tylerhunt
Copy link

Thanks, @ilyakatz. Came across this when trying to fix error handling in the app I based my blog post on. 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment