[RUBY] Output Rails Routes as csv

What did you write

How to output Rails routes list in csv format

→ When catching up the system in a new organization, it can be used when you want to trace from the routing and get a bird's-eye view of the whole, and you want to systematically summarize the information in SpreadSheet etc.

How to do

Reference source

See rails routes implementation https://github.com/rails/rails/blob/5ccdd0bb6d1262a670645ddf3a9e334be4545dac/railties/lib/rails/tasks/routes.rake ――It seems good to pack all Route information in ʻinspector and format it with .format () . --It seems good to create your own Formatter by imitating the implementation of ConsoleFormatter`

Practice

Cut a suitable branch

--Since this information is output for personal understanding, cut an appropriate branch locally so as not to affect the production source.

Create 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

Run

bin/rails route_formatter:csv

--If you want to put it on the Clipboard on Mac,

bin/rails route_formatter:csv | pbcopy

--The rest is processed by Excel or SpreadSheet

Reference link

Recommended Posts

Output Rails Routes as csv
[Ruby on Rails] CSV output function
How to output CSV created by Rails to S3
csv file output with opencsv
How to read rails routes
CSV output with Apache Commons CSV
Supports 0 drop in CSV output
Csv output processing using super-csv
Rewrite Routes in Rails Engine
[Rails] Implementation of CSV import function
Explanation of the order of rails routes
[Rails] Implementation of CSV export function
Implement CSV download function in Rails