如何找到Ruby方法依赖项?

时间:2022-11-04 07:16:13

Is there a way to get the list of methods that implement a Ruby method when this method is invoked?

有没有办法在调用此方法时获取实现Ruby方法的方法列表?

For example:

def foo
  puts "foo"
end

def foo2
  foo
end

I want to know that when calling "foo2" it calls 1st "foo" and 2nd "puts" and the corresponding files these methods are defined into. (If "puts" calls other methods, I would like to know them too)

我想知道,当调用“foo2”时,它调用1st“foo”和第二个“puts”以及这些方法定义的相应文件。 (如果“put”调用其他方法,我也想知道它们)

Is that possible? and if 'yes' how? I could say that my question is about finding the method dependencies.

那可能吗?如果'是'怎么样?我可以说我的问题是找到方法依赖项。

2 个解决方案

#1


4  

You can sort of get this using set_trace_func, but since Ruby is dynamic you would also need test code to call the methods so that the call order is printed.

您可以使用set_trace_func进行此操作,但由于Ruby是动态的,您还需要测试代码来调用方法以便打印调用顺序。

set_trace_func proc { |event, filename, line, id, binding, klass| puts "#{klass}##{id}" }

In Ruby 2.0, TracePoint is a superior alternative.

在Ruby 2.0中,TracePoint是一种更好的选择。

#2


4  

Static code analysis, especially one you'd like to perform (listing all methods called within a method), is very hard in ruby (close to impossible) because the language is dynamic and allows for very strong metaprogramming techniques. Even the parser itself doesn't know the methods required until it tries to execute the code.

静态代码分析,特别是你想要执行的代码(列出方法中调用的所有方法),在ruby中非常难(几乎不可能),因为语言是动态的并且允许非常强大的元编程技术。甚至解析器本身也不知道在尝试执行代码之前所需的方法。

Example: calling eval with code read from a file.

示例:使用从文件读取的代码调用eval。

#1


4  

You can sort of get this using set_trace_func, but since Ruby is dynamic you would also need test code to call the methods so that the call order is printed.

您可以使用set_trace_func进行此操作,但由于Ruby是动态的,您还需要测试代码来调用方法以便打印调用顺序。

set_trace_func proc { |event, filename, line, id, binding, klass| puts "#{klass}##{id}" }

In Ruby 2.0, TracePoint is a superior alternative.

在Ruby 2.0中,TracePoint是一种更好的选择。

#2


4  

Static code analysis, especially one you'd like to perform (listing all methods called within a method), is very hard in ruby (close to impossible) because the language is dynamic and allows for very strong metaprogramming techniques. Even the parser itself doesn't know the methods required until it tries to execute the code.

静态代码分析,特别是你想要执行的代码(列出方法中调用的所有方法),在ruby中非常难(几乎不可能),因为语言是动态的并且允许非常强大的元编程技术。甚至解析器本身也不知道在尝试执行代码之前所需的方法。

Example: calling eval with code read from a file.

示例:使用从文件读取的代码调用eval。