Skip to Content

Rails - Export all routes to csv file

Posted on

This task allows us to export all routes to CSV file.

  • Step 1: Generate task file
bundle exec rails g task route_formatter csv
  • Step 2: Write rake test
# 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
  • Step 3: Run
bin/rails route_formatter:csv

# Or run task and copy to clipboard, and you can paste to csv file
bin/rails route_formatter:csv | pbcopy

Reference

comments powered by Disqus