Skip to content

Commit 4df3a8a

Browse files
committed
feat: エラーページのプレビュー機能を動的に改善
エラーの種類ごとにアクションやルートを追加する必要があった 静的なプレビュー機能を、URLのステータスコードを元に 動的にページを出し分ける、よりDRYな構成にリファクタリング。 - に アクションを実装 - ルートを に一本化 - これにより、今後のメンテナンス性が大幅に向上します
1 parent 619801e commit 4df3a8a

File tree

2 files changed

+14
-18
lines changed

2 files changed

+14
-18
lines changed
Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
class Previews::ErrorsController < ApplicationController
2-
# このコントローラー全体で、application.html.erb のレイアウトを使用します
32
layout "application"
43

5-
# 404ページをプレビューするためのアクション
6-
def not_found
7-
# app/views/errors/not_found.html.erb を、
8-
# ステータスコード404で描画します
9-
render template: "errors/not_found", status: :not_found
10-
end
4+
def show
5+
status_code = params[:status_code].to_i
116

12-
# 422ページをプレビューするためのアクション
13-
def unprocessable_entity
14-
render template: "errors/unprocessable_entity", status: :unprocessable_entity
15-
end
7+
if status_code == 422
8+
# 422の時だけは、ファイル名を直接指定
9+
# Rails標準のRack::Utilsは422を "Unprocessable Content" と解釈しますが、
10+
# Rambulanceが期待するビュー名は `unprocessable_entity.html.erb` です。
11+
# この食い違いを吸収するため、422の時だけファイル名を直接指定しています。
12+
error_page_name = "unprocessable_entity"
13+
else
14+
error_page_name = Rack::Utils::HTTP_STATUS_CODES[status_code].downcase.gsub(" ", "_")
15+
end
1616

17-
# 500ページをプレビューするためのアクション
18-
def internal_server_error
19-
render template: "errors/internal_server_error", status: :internal_server_error
17+
render template: "errors/#{error_page_name}", status: status_code
2018
end
19+
2120
end

config/routes.rb

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,7 @@
113113

114114
if Rails.env.development?
115115
namespace :previews do
116-
# /previews/errors/404 などのURLでアクセスできるようになります
117-
get "errors/404" => "errors#not_found"
118-
get "errors/422" => "errors#unprocessable_entity"
119-
get "errors/500" => "errors#internal_server_error"
116+
get "errors/:status_code", to: "errors#show"
120117
end
121118
end
122119

0 commit comments

Comments
 (0)