I have the following code:
code = "def hi; \"hi!\"; end"
eval code
hi == "hi!" # true
I can access the method hi, because when it is defined in the evaluated code, it is defined as a method of the main object.
However, this also means that the evaluated code can access things I define outside of it:
def hi; "hi!"; end
eval "hi == \"hi\"" # => true
I want to have a separate namespace in which I can run evaluated code; How would I do it?
I tried playing with module_eval and using a module for the namespace, but I can’t get it to define a method or a class and access that in another evaluation.
You can evaluate code inside of an object like this:
With this you can control whether to preserve definitions between evals or not: you can reuse
containerinstance or dispose it and create new one. This would work with method definitions and constants, local variables aren’t preserved between such calls.Also, instead of
Objectyou may want to look atBlankStatepattern. “blankslate” is an example.