如何使用反射获取参数名称 [英] How to get argument names using reflection
问题描述
我想在 Ruby 中做一些相当繁重的反射.我想创建一个函数,该函数返回调用堆栈更高层的各种调用函数的参数名称(仅高一个就足够了,但为什么要停在那里?).我可以使用 Kernel.caller
,转到文件并解析参数列表,但这会很丑陋且不可靠.
I would like to do some fairly heavy-duty reflection in Ruby. I want to create a function that returns the names of the arguments of various calling functions higher up the call stack (just one higher would be enough but why stop there?). I could use Kernel.caller
, go to the file and parse the argument list but that would be ugly and unreliable.
我想要的功能将按以下方式工作:
The function that I would like would work in the following way:
module A
def method1( tuti, fruity)
foo
end
def method2(bim, bam, boom)
foo
end
def foo
print caller_args[1].join(",") #the "1" mean one step up the call stack
end
end
A.method1
#prints "tuti,fruity"
A.method2
#prints "bim, bam, boom"
我不介意使用 ParseTree 或一些类似的工具来完成这项任务,但看看 Parsetree,如何将其用于此目的并不明显.创建像 this 这样的 C 扩展是另一种可能性,但如果有人已经为我做的.
I would not mind using ParseTree or some similar tool for this task but looking at Parsetree, it is not obvious how to use it for this purpose. Creating a C extension like this is another possibility but it would be nice if someone had already done it for me.
我可以看出我可能需要某种 C 扩展.我想这意味着我的问题是 C 扩展的哪种组合最容易工作.我不认为 caller+ParseTree 本身就足够了.
I can see that I'll probably need some kind of C extension. I suppose that means my question is what combination of C extension would work most easily. I don't think caller+ParseTree would be enough by themselves.
至于我为什么要这样做,与其说自动调试",不如说我想用这个功能来自动检查函数的调用和返回条件:>
As far as why I would like to do this goes, rather than saying "automatic debugging", perhaps I should say that I would like to use this functionality to do automatic checking of the calling and return conditions of functions:
def add x, y
check_positive
return x + y
end
如果 x
和 y
不是正数,check_positive
会抛出异常.显然,还有更多内容,但希望这能提供足够的动力.
Where check_positive
would throw an exception if x
and y
weren't positive. Obviously, there would be more to it than that but hopefully this gives enough motivation.
推荐答案
我建议你看看 Merb 的 action-args 库.
I suggest you take a look at Merb's action-args library.
require 'rubygems'
require 'merb'
include GetArgs
def foo(bar, zed=42)
end
method(:foo).get_args # => [[[:bar], [:zed, 42]], [:zed]]
如果你不想依赖 Merb,你可以从 github 中的源代码.
If you don't want to depend on Merb, you can choose and pick the best parts from the source code in github.
这篇关于如何使用反射获取参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!