开发者

Access local variables from a different binding in Ruby

开发者 https://www.devze.com 2023-03-17 07:02 出处:网络
In Ruby, you can easily access local variables programmatically by using local_variables and eval. I would really 开发者_如何学编程like to have meta-programming access to these variables using a singl

In Ruby, you can easily access local variables programmatically by using local_variables and eval. I would really 开发者_如何学编程like to have meta-programming access to these variables using a single method call such as

# define a variable in this scope, such as
x = 5
Foo.explore_locals  # inside the Foo#explore_locals method, access x

where Foo is some external module. The idea is to display and export local variables in a nice way.

What should be inside the explore_locals method? Is there any way to make this possible? If absolutely necessary, I guess it could be

Foo.explore_locals binding

but this is much less elegant for the application I have in mind.


It's a shame there isn't a built-in way to get the caller's binding. The block trick seems to be the usual answer to this question.

However there is another 'trick' which existed for older 1.8 Ruby versions called binding_of_caller. Looks like quix ported it to 1.9. You might want to check that out:

https://github.com/quix/binding_of_caller


Here is an example (but it requires extra braces {} which I would rather avoid if possible):

module Foo
  def self.explore_locals &block
    p block.binding.eval 'local_variables'
  end
end

local_1 = 3
Foo.explore_locals{}  # shows [:local_1, :_]
0

精彩评论

暂无评论...
验证码 换一张
取 消