从 Ruby 中的不同绑定访问局部变量

Pet*_*ter 5 ruby metaprogramming

local_variables在 Ruby 中,您可以使用和以编程方式轻松访问局部变量eval。我真的很想使用单个方法调用对这些变量进行元编程访问,例如

# define a variable in this scope, such as
x = 5
Foo.explore_locals  # inside the Foo#explore_locals method, access x
Run Code Online (Sandbox Code Playgroud)

Foo一些外部模块在哪里。这个想法是以一种很好的方式显示和导出局部变量。

方法内部应该包含什么explore_locals?有没有办法让这成为可能?如果绝对有必要的话,我想可能是

Foo.explore_locals binding
Run Code Online (Sandbox Code Playgroud)

但这对于我想要的应用程序来说不太优雅。

Cas*_*per 1

遗憾的是没有内置方法来获取调用者的绑定。块技巧似乎是这个问题的常见答案。

然而,旧的 1.8 Ruby 版本还存在另一个“技巧”,称为binding_of_caller. 看起来 quix 将其移植到了 1.9。您可能想检查一下:

https://github.com/quix/binding_of_caller