我已经用 Ruby on Rails 编写了一个 API,我希望有一个页面列出所有可用的路由(我知道这可以通过命令行使用 rake routes
完成)。
我想自动生成它,而不必在更新代码时自己更新它。有没有办法获取 Controller (或 View )中所有路由的列表?
最佳答案
我开始探索 jvnill 给出的解决方案,并在文档中发现它指出 RouteInspector should not be used .出于什么原因我不知道,但我决定看一下代码,然后尝试获得更有用的输出,而不仅仅是字符串。我使用 jvnill 的代码作为起点。
all_routes = Rails.application.routes.routes
routes = all_routes.routes.collect do | route |
reqs = route.requirements
controller = reqs[:controller] || ':controller'
action = reqs[:action] || ':action'
constraints = reqs.except(:controller, :action)
verb = route.verb.source.gsub(/[$^]/, '')
{name: route.name.to_s, verb: verb, path: route.path.spec.to_s, reqs: reqs}
end
routes.reject! { |r| r[:path].starts_with?("/rails/info/properties") || r[:path] == "#{Rails.application.config.assets.prefix}" }
routes
然后包含一个散列,其中包含路由名称、路径以及 Controller 和 Action 。
关于ruby-on-rails - 在 View / Controller 中显示路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686761/