您可以非常简单地通过使用rails routes 命令查看rails dumps the routes 来做到这一点。
# frozen_string_literal: true
require "rails/command"
module Rails
module Command
class RoutesCommand < Base # :nodoc:
class_option :controller, aliases: "-c", desc: "Filter by a specific controller, e.g. PostsController or Admin::PostsController."
class_option :grep, aliases: "-g", desc: "Grep routes by a specific pattern."
class_option :expanded, type: :boolean, aliases: "-E", desc: "Print routes expanded vertically with parts explained."
def perform(*)
require_application_and_environment!
require "action_dispatch/routing/inspector"
say inspector.format(formatter, routes_filter)
end
private
def inspector
ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes.routes)
end
def formatter
if options.key?("expanded")
ActionDispatch::Routing::ConsoleFormatter::Expanded.new
else
ActionDispatch::Routing::ConsoleFormatter::Sheet.new
end
end
def routes_filter
options.symbolize_keys.slice(:controller, :grep)
end
end
end
end
这里的关键是:
inspector.format(formatter, routes_filter)
格式化程序实际上只是一个响应section、header 和result 的类:
# formats routes as a simple array of hashes
class HashFormatter
def initialize
@buffer = []
end
# called for the main routes and also for each
# mounted engine
def section(routes)
routes.each do |r|
@buffer << r.slice(:name, :verb, :path)
end
end
# this method does not need to do anything since the "headers" are
# part of the hashes
def header(routes)
end
def result
@buffer
end
end
然后我们可以调用我们的格式化程序:
inspector = ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes)
inspector.format(HashFormatter.new)
并得到一个哈希数组:
[{:name=>"", :verb=>"GET", :path=>"/pizzas/:foo(.:format)"}, {:name=>"", :verb=>"GET", :path=>"/pizzas/:foo/:bar(.:format)"}, {:name=>"", :verb=>"GET", :path=>"/pizzas/:foo/:bar/:baz(.:format)"}, {:name=>"foo", :verb=>"DELETE", :path=>"/foo(.:format)"}, {:name=>"root", :verb=>"GET", :path=>"/"}, #...]
这里的优点是您可以利用现有代码收集任何已安装引擎的路由并拒绝内部路由。