如何在 ruby​​ on rails 中获取控制器和动作列表? [英] How to get list of controllers and actions in ruby on rails?

查看:31
本文介绍了如何在 ruby​​ on rails 中获取控制器和动作列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails中,我可以通过controller_name获取当前控制器的名称,通过调用action_name获取当前动作.我正在寻找类似的运行时反射来获取以下内容:

In rails, I can get the name of the current controller via controller_name and the current action by calling action_name. I am looking for similar runtime reflection for fetching the following:

  1. 应用程序中所有控制器的列表.
  2. 给定控制器中所有操作的列表.

例如,我是一个具有添加"和编辑"操作的产品控制器.我可以以编程方式提取这些操作的名称以向用户显示支持哪些操作吗?

For example, I a Product controller which has "add" and "edit" actions. Can I pull the names of these actions programmatically to show the user what operations are supported?

我查看了一个调用 ActionController::Routing::Routes.named_routes.routes.each 的方法但我无法让它发挥作用.我在使用它时遇到了未初始化的常量 ActionDispatch::Routing::Routes 错误.

I have looked at a method that calls for use of ActionController::Routing::Routes.named_routes.routes.each but I could not get that to work. I got uninitialized constant ActionDispatch::Routing::Routes error when I used it.

如果有什么好的教程或者文档可以帮助我理解rails是如何反射能力的.我搜索了它,但我主要得到了与活动记录反射相关的博客.我正在寻找可以让我在运行时获取有关控制器和操作/方法的信息的东西.
谢谢,

If there is any good tutorial or document that can help me understand how rails reflection capabilities. I searched for it but I mostly got active record reflection related blogs. I am looking for something that lets me get information on controllers and actions/methods at run time.
Thanks,

塔布雷兹

推荐答案

获取控制器类列表的最简单方法是:

The easiest way to get a list of controller classes is:

ApplicationController.descendants

但是,由于类是延迟加载的,因此在执行此操作之前,您需要预先加载所有类.请记住,此方法需要时间,并且会减慢您的启动速度:

However, as classes are loaded lazily, you will need to eager load all your classes before you do this. Keep in mind that this method will take time, and it will slow down your boot:

Rails.application.eager_load!

要获取控制器中的所有动作,请使用 action_methods

To get all the actions in a controller, use action_methods

PostsController.action_methods

这将返回一个 Set ,其中包含控制器中作为动作"的所有方法的列表(使用与 Rails 用于确定方法是否是要路由到的有效动作相同的逻辑)的列表).

This will return a Set containing a list of all of the methods in your controller that are "actions" (using the same logic Rails uses to decide whether a method is a valid action to route to).

这篇关于如何在 ruby​​ on rails 中获取控制器和动作列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆