LoginSignup
3
1

More than 3 years have passed since last update.

RailsのRoutesをcsvで出力

Posted at

何を書いた記事か

Railsのroutes一覧をcsv形式で出力する方法

→ 新しい組織でシステムキャッチアップする際、ルーティングから辿って全体を俯瞰したい、その情報を体系的にSpreadSheetなどにまとめたい場合に利用できる

どうやるか

参考になるソース

railsのroutesの実装を参照
https://github.com/rails/rails/blob/5ccdd0bb6d1262a670645ddf3a9e334be4545dac/railties/lib/rails/tasks/routes.rake
- inspector に全てのRoute情報を詰めて、 .format() で整形すれば良さそう
- ConsoleFormatter の実装を真似て独自のFormatterを作れば良さそう

実践

適当なブランチを切る

  • 個人的な理解のために出力する情報なので、本番ソースに影響ださないよう、ローカルで適当なブランチを切る

taskを作成

$ bundle exec rails g task route_formatter csv
lib/tasks/route_formatter.rake
namespace :route_formatter do
  desc "get route as csv format"
  task csv: :environment do |t|
    class CSVFormatter
      def initialize
        @buffer= []
      end

      def result
        @buffer.join("\n")
      end

      def section_title(title)
      end

      def section(routes)
        routes.each do |r|
          @buffer << [r[:name], r[:verb], r[:path], r[:reqs]].join(",")
        end
      end

      def header(routes)
        @buffer << %w"Prefix Verb URI_Pattern Controller#Action".join(",")
      end

      def no_routes
        @buffer << ""
      end
    end
    require "action_dispatch/routing/inspector"
    all_routes = Rails.application.routes.routes
    inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes)
    puts inspector.format(CSVFormatter.new, ENV['CONTROLLER'])
  end

end

実行

bin/rails route_formatter:csv
  • MacでClipboardに入れたい場合は下記
bin/rails route_formatter:csv | pbcopy
  • あとはExcelとかSpreadSheetで処理

参考リンク

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1