Problem when calling from Ruby->Java->Ruby


#1

Hi,

I am trying to have jruby.bat invoke my ruby script which then calls a
Java function. Inside my java function, I want to be able to call back
my ruby script (for example, invoke method on some ruby object that was
created initially by the ruby script). I wonder how I can accomplish
this?

I follow the instruction and did the following:

[ruby script]

class Tool
def some_ruby_func
puts :foo.hash
end

end

puts :foo.hash
a = com.foo.Foo.new
a.foo(Tool.new)

[java code]
public class Foo {
public void foo(RubyObject o) throws Exception
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(“jruby”);
engine.put(“tool”, o);
engine.eval("$tool.some_ruby_func");
}
}

As the result, the first “puts :foo.hash” will end up be different than
the second output of the “puts :foo.hash”. This causes a huge problem
when I have hash that uses symbol as the key.
I guess this cause of this is because I am printing the symbol via 2
different ruby runtime engine instance? If so, I wonder if there is
anyway I can get the “current” running script engine runtime instead of
having to create a new instance of it?

Appreciated for your help.

Thanks,
–Gary


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email

#2

On Fri, Feb 20, 2009 at 12:21 AM, Gary L. removed_email_address@domain.invalid wrote:


As the result, the first “puts :foo.hash” will end up be different than the
second output of the “puts :foo.hash”. This causes a huge problem when I
have hash that uses symbol as the key. I guess this cause of this is because
I am printing the symbol via 2 different ruby runtime engine instance? If
so, I wonder if there is anyway I can get the “current” running script
engine runtime instead of having to create a new instance of it?

Appreciated for your help.

Today we don’t have any notion of “current” runtime or a
straightforward way of getting at it from bare Java code. But since
you’re passing a RubyObject you can just call the method on it
directly:

[java code]
public class Foo {
public void foo(RubyObject o) throws Exception {
Ruby runtime = o.getRuntime();
o.callMethod(runtime.getCurrentContext(), “some_ruby_func”);
}
}

Cue the obligatory mention of coupling to JRuby-specific APIs, but if
you’re willing to live with that, the above approach should work fine.

/Nick


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email