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

查看:287
本文介绍了如何获取控制器和操作列表在ruby在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.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,

Tabrez

推荐答案

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

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在rails?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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