ドキュメントとしてルーティング定義をマークダウンで書き出したかったので、実装してみました。
動作環境
- Rails5
方針
-
rake routes
の実装をパクる
https://github.com/rails/rails/blob/5ccdd0bb6d1262a670645ddf3a9e334be4545dac/railties/lib/rails/tasks/routes.rake -
独自の
Formatter
を作れば良さそう(ダックタイピング)
https://github.com/rails/rails/blob/63f0c04850dd0bcdc7d35266e81fa1a7778570a8/actionpack/lib/action_dispatch/routing/inspector.rb#L129-L185
実装
lib/tasks/routes.rake
namespace :routes do
desc "Exports routing to docs/routing.md"
task export: :environment do
all_routes = Rails.application.routes.routes
require 'action_dispatch/routing/inspector'
inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes)
md = inspector.format(MarkdownFormatter.new, ENV['CONTROLLER'])
File.open('docs/routing.md', 'w') do |f|
f.puts "\# #{Rails.application.class.parent_name.camelize} all routing\n\n" << md
end
end
private
class MarkdownFormatter
def initialize
@buffer = []
@current_section = "Application"
end
def result
@buffer.join("\n")
end
def section_title(title)
@current_section = title
end
def section(routes)
routes.each do |r|
@buffer << "#{r[:name]}|#{r[:verb]}|#{r[:path]}|#{r[:reqs]}"
end
end
def header(routes)
@buffer << "Prefix|Verb|URI Pattern|Controller#Action\n---|---|---|---"
end
def no_routes
@buffer << ""
end
end
end
実行
$ rake routes:export
もしくは
$ rails routes:export
結果
docs/routing.md
# SampleApp all routing
Prefix|Verb|URI Pattern|Controller#Action
---|---|---|---
new_user_session|GET|/users/sign_in(.:format)|devise/sessions#new
user_session|POST|/users/sign_in(.:format)|devise/sessions#create
destroy_user_session|DELETE|/users/sign_out(.:format)|devise/sessions#destroy
new_user_password|GET|/users/password/new(.:format)|devise/passwords#new
edit_user_password|GET|/users/password/edit(.:format)|devise/passwords#edit
user_password|PATCH|/users/password(.:format)|devise/passwords#update
|PUT|/users/password(.:format)|devise/passwords#update
|POST|/users/password(.:format)|devise/passwords#create
cancel_user_registration|GET|/users/cancel(.:format)|devise/registrations#cancel
new_user_registration|GET|/users/sign_up(.:format)|devise/registrations#new
edit_user_registration|GET|/users/edit(.:format)|devise/registrations#edit
user_registration|PATCH|/users(.:format)|devise/registrations#update
|PUT|/users(.:format)|devise/registrations#update
|DELETE|/users(.:format)|devise/registrations#destroy
|POST|/users(.:format)|devise/registrations#create
new_user_confirmation|GET|/users/confirmation/new(.:format)|devise/confirmations#new
user_confirmation|GET|/users/confirmation(.:format)|devise/confirmations#show
|POST|/users/confirmation(.:format)|devise/confirmations#create
参考