Feature #6710
closednew special binding specifier :isolated
Description
=begin
= Abstract
New special binding specifier :isolated for the 2nd argument of eval() method.
eval(src, :isolated) evaluates src' program on the same environment as
require' and 'load'.
It is a bit different from `TOPLEVEL_BINDING'.
= Background
We have TOPLEVEL_BINDING to evaluate source code on the main environment (self is `main', and so on).
However, TOPLEVEL_BINDING contains local variables which are evaluated in toplevel.
For example:
x = 10
eval('a=1', TOPLEVEL_BINDING)
eval('b=2', TOPLEVEL_BINDING)
eval('c=3', TOPLEVEL_BINDING)
eval('p (a+b+c) * x', TOPLEVEL_BINDING) #=> 60
To simulate "require()" or "load()" method, the eval() method with TOPLEVEL_BINDING is not enough (require() and load() methods don't evaluate scripts within main' environment. Similar to
main' environment (self == main), but local variables aren't taken over).
BTW, eval() receive special binding specifier `nil' (which means current binding).
= Proposal
Introduce the new special binding specifier :isolated for the 2nd argument of eval() method.
eval(src, :isolated) evaluates src' program on the new binding, which is same environment as
require' and 'load'.
== Usecase
Users can define toplevel methods, modules, classes on the any places.
def m
# define toplevel method foo()
eval('def foo(); end', :isolated)
# define ::Bar class
eval('class Bar; end', :isolated)
end
Users can make your own alternative require() method.
def my_require(feature)
... # set src from feature
eval(src, :isolated)
...
end
== Consideration
- :isolated is good name or not?
I'm not sure the `isolated' is good name or not.
- ISOLATED_BINDING = :isolated
If make default constants ::ISOLATED_BINDING as a :isolated, then we can use it as `eval(src, ISOLATED_BINDING)', similar manner with TOPLEVEL_BINDING.
= Acknowledgment
Usa-san proposed the name isolated'. My first idea of this name is
empty'.
=end