如何从给定代码快速分析代码定义

时间:2017-05-11 18:01:42

标签: ruby-on-rails ruby rubygems

让我们说我是一个非常庞大的项目,我很好奇这条线是如何工作的:

authorize! :read_pipeline_schedule, user_project

authorize!应该是方法名称。它是类中的私有函数,还是从父块提供的DSL,包含或在gem中声明的?或者也许没有?

我使用grep查找内部代码,使用Google搜索gems等外部代码,但是如果我能看到方法的调用堆栈,我认为这很有用。 puts caller正在从我所在的地方打印,尽管它不能用于分析上述情况。

我想知道最佳做法。

2 个答案:

答案 0 :(得分:0)

最简单的方法是询问方法本身:

method_object = method(:authorize!)

method_object.owner
# => returns module in which the method resides

method_object.source_location
# => returns file name and line number of source code where the method is defined

请注意,对于没有Ruby源代码的方法,source_location可能会返回nil,例如在解释器内部实现的动态生成的方法或方法(YARV中的C函数,JRuby中的Java方法等)

答案 1 :(得分:0)

我喜欢caller(0)caller_locations,以及令人难以置信的show-source