开发者

How can I eval code in JRuby, in a new context every time?

开发者 https://www.devze.com 2023-04-02 20:02 出处:网络
I want to allow evaluation of code in a shell-like app. At a press of a button, the code will be evaluated and a result will be showed to the user. I want to make it so that if he evaluates code again

I want to allow evaluation of code in a shell-like app. At a press of a button, the code will be evaluated and a result will be showed to the user. I want to make it so that if he evaluates code again, everything defined in old evaluation will no longer exist. For example, imagine this is eval #1:

puts "Hello world"
user_variable1  = 10
$USER_VARIABLE2 = 20

I want that on eval #2, the values of user_variable1 and $USER_VA开发者_如何学PythonRIABLE2 not to exist. This is why I'm thinking of using some kind of context on each run. However, I don't know where to look for more info.


You could just run another (or the same script) in another process using some way of executing the commands. Something like

system('myscript.rb')

or

`myscript.rb`

This will ensure that any variables are cleared, however, the environment variables will of course be the same. Since ruby 1.9 you can reset them too, though. Like so:

system('myscript.rb', :unsetenv_others => true)

If you want something very close to the eval() function, you could create an eval.rb, that will just evaluate the first parameter and then define an evalExt function:

eval.rb:

eval(ARGV[0])

And then in your other script: def evalExt(script) system("eval.rb \"#{script}\"", :unsetenv_others => true) end

evalExt('puts "test"')
evalExt('puts "test1"')

In case of JRuby you should be able to invoke another ruby engine as easily, by calling Java code from JRuby and then using the ScriptEngineManager as described on Wikipedia:

require 'java'

mgr = ScriptEngineManager.new();
rbEngine = mgr.getEngineByExtension("rb");

def evalExt(script)
   rbEngine.eval(script);
end

Maybe you will have to ensure to reset the script context or bindings (see this article).

All that said, maybe the easiest solution would be to just ensure that no global variables are set, then you do not have to seperate contexts at all.

0

精彩评论

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

关注公众号