如何以编程方式列出 Rails 中的所有控制器 [英] How to programmatically list all controllers in Rails
问题描述
我正在尝试构建一个 RESTful 应用程序来实际管理许多类型的可配置对象,因此有大量的资源"类型,因此有很多控制器.我仍处于 POC 阶段,所以如果我能在第一个导航页面中显示所有控制器会很好,所以有什么简单的方法(可编程)来做到这一点?
I'm trying to build a RESTful app to actually manage many kind of configurable objects, so there are a large amount of "resource" types, and hence a lot of controllers. I'm still at the POC phase, so it will be nice if I can show all controllers in a first navigation page, so any easy way (programmable) to do that?
推荐答案
在 Rails 3.1+ 中:
In Rails 3.1+:
Rails.application.routes
如果你的 routes.rb 文件中有它们的路径,这将为你提供所有控制器、动作和它们的路由.
This will give you all the controllers, actions and their routes if you have their paths in your routes.rb file.
例如:
routes= Rails.application.routes.routes.map do |route|
{alias: route.name, path: route.path, controller: route.defaults[:controller], action: route.defaults[:action]}
end
更新:对于Rails 3.2,日志引擎路径改变了,所以代码变成:
Update: For Rails 3.2, Journal engine path changed, so the code becomes:
routes= Rails.application.routes.routes.map do |route|
{alias: route.name, path: route.path.spec.to_s, controller: route.defaults[:controller], action: route.defaults[:action]}
end
更新:仍在为 Rails 4.2.7 工作.要提取控制器列表(根据实际问题),您只需提取控制器和 uniq
Update:
Still working for Rails 4.2.7. To extract the list of controllers (per actual question), you can simply extract the controller and uniq
controllers = Rails.application.routes.routes.map do |route|
route.defaults[:controller]
end.uniq
这篇关于如何以编程方式列出 Rails 中的所有控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!