Skip to content

Instantly share code, notes, and snippets.

@timm-oh
Created March 13, 2022 16:30
Show Gist options
  • Save timm-oh/fb075595aafc4ea4ffce07a031bf9d79 to your computer and use it in GitHub Desktop.
Save timm-oh/fb075595aafc4ea4ffce07a031bf9d79 to your computer and use it in GitHub Desktop.
ERB in error templates without a custom controller
<!-- app/views/errors/500.html.erb -->
<!DOCTYPE html>
<html>
<head>
<title><%= "SUPER COOL TITLE" %></title>
</head>
</html>
# config/application.rb
# Might need to require the exception app here. Depends on your setup.
# require 'APP_NAME/public_exceptions'
module APP_NAME
class Application < Rails::Application
config.exceptions_app = APP_NAME::PublicExceptions.new(
Rails.public_path,
Rails.root.join('app/views/errors').to_s
)
# Other config stuff
end
end
# lib/app_name/public_exceptions.rb
class APP_NAME::PublicExceptions < ActionDispatch::PublicExceptions
attr_reader :errors_path
def initialize(public_path, errors_path)
super(public_path)
@errors_path = errors_path.chomp("/")
end
private
def render_html(status)
path = "#{errors_path}/#{status}.html.erb"
if File.exist?(path)
raw = File.read(path)
erb = ERB.new(raw).result(binding)
render_format(status, "text/html", erb)
else
super(status)
end
end
end
@timm-oh
Copy link
Author

timm-oh commented Apr 17, 2022

Would this be considered the "standard" approach?

# config/routes.rb
...
match '/404', :to => 'errors#error_404', :via => :all
match '/500', :to => 'errors#error_500', :via => :all
...
# app/controllers/errors_controller.rb
class ErrorsController < ApplicationController

  def error_404
    render(:status => 404)
  end

  def error_500
    @error_id = Raven.last_event_id
    render(:status => 500)
  end

end
<!-- app/views/errors/error_404.html.erb -->
<!DOCTYPE html>
<html>
  <head>
    <title><%= "SUPER COOL TITLE" %></title>
  </head>
  <body>
    <%= @error_id %>
  </body>
</html>
<!-- app/views/errors/error_500.html.erb -->
<!DOCTYPE html>
<html>
  <head>
    <title><%= "SUPER COOL TITLE" %></title>
  </head>
  <body>
    <%= @error_id %>
  </body>
</html>

Yes

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