Accessing local variables from another binding in Ruby

In Ruby, you can easily access local variables programmatically using local_variables and eval . I would really like to have metaprogramming access to these variables using one method call, for example

 # 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 beautiful way.

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

 Foo.explore_locals binding 

but it is much less elegant for the application that I mean.

+4
source share
2 answers

It is a shame that there is no built-in way to get the caller’s binding. This trick seems to be the usual answer to this question.

However, there is another β€œtrick” that existed for earlier versions of 1.8 Ruby called binding_of_caller . It looks like quix has ported it to 1.9. You can check this out:

https://github.com/quix/binding_of_caller

+1
source

Here is an example (but this requires additional brackets {} , 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, :_] 
+1
source

Source: https://habr.com/ru/post/948531/


All Articles