I’m rather new to Ruby, and so far, figuring out how to use “binding” objects is one of the biggest pain points for me. If I’m reading the documentation correctly, they’re almost entirely opaque. To access the scope inside the binding object, you have to have a string of Ruby code and eval it using the binding.
Maybe I’m just a purist from a different school, but I’m allergic to string-based ‘eval’ constructs, generally speaking. Is there any way to do any of the following, securely and in the general case, given a binding object:
- List the identifiers in scope in the context the binding represents, or retrieve a hash of the contents.
- Set the value of a local variable in the binding equal to that of some local variable in an external context. Ideally, this should work generally, even if the value is an object reference, file handle, or some other complex entity.
- (extension 2:) Given a hash, set locals in the binding for each entry.
- Better yet, given a hash build a binding with only the basic language constructs and the names in the hash in scope.
Basically, I want to know which of those is possible and how to accomplish the ones that are. I imagine that the solutions for each will be fairly closely related, which is why I’m putting all of this in a single question.
Alternatively, is there any way to eval code that’s already been parsed in the context of a binding, similar to Perl’s eval BLOCK syntax?
On searching more, I found an answer to at least part of my question:
Based on: http://wikis.onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc/style/print
The rest is from experimentation after Jim Shubert’s helpful pointers.
eval-inglocal_variables,instance_variablesandglobal_variablesinside the binding.var_name,new_val,my_binding(syntax may be imperfect or improvable, feel free to suggest in comments. Also, I couldn’t get the code formatting to work inside the list, suggestions for how to do that will also be implemented.)This does involve using string
eval. However, no variable values are ever expanded into the strings involved, so it should be fairly safe if used as described, and should work to ‘pass in’ complex variable values.Also note that it’s always possible to do
eval var_name, my_bindingto get a variable’s value. Note that in all of these uses it’s vital that the variable’s name be safe to eval, so it should ideally not come from any kind of user input at all.Setting a variable inside a binding given
var_name,new_val,my_binding:Building a “bespoke” binding: