Gregor
Gregor

Reputation: 3027

JRuby does not see variable bindings

For some reason jruby does not see the variable bindings set in Java. The following example should, according to the documentation here https://github.com/jruby/jruby/wiki/Embedding-with-JSR-223, work:

public static void main(String[] args) throws ScriptException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("jruby");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("owner", "Otto");
    engine.eval("puts \"hello #{owner}\"", bindings);
}

In my test I get the exception:

NameError: undefined local variable or method `owner' for main:Object
  <top> at <script>:1
Exception in thread "main" javax.script.ScriptException: org.jruby.embed.EvalFailedException: (NameError) undefined local variable or method `owner' for main:Object

did I miss anything?

Upvotes: 1

Views: 282

Answers (1)

Gregor
Gregor

Reputation: 3027

The reason for that behavior is that the local variables by default can not be shared between Java and JRuby, but only global variables. See: https://github.com/jruby/jruby/wiki/RedBridge on local variable behavior. The solution is to explicitly set either

System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");

or

System.setProperty("org.jruby.embed.localvariable.behavior",
"transient");

In the first case the local variables are kept across evaluations, in the later case they are per evaluation.

Upvotes: 1

Related Questions