Skip to content

Instantly share code, notes, and snippets.

@colinsurprenant
Last active December 31, 2018 04:59
Show Gist options
  • Save colinsurprenant/6089693 to your computer and use it in GitHub Desktop.
Save colinsurprenant/6089693 to your computer and use it in GitHub Desktop.
calling JRuby from Java example
import org.jruby.Ruby;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
public class CallJRuby {
private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
public static void main(String[] ARGV) {
// load script
String bootstrap = "require './myrubyclass'";
__ruby__.evalScriptlet(bootstrap);
// retrieve namespaced class using getClassFromPath, instantiate object, call method
RubyModule rclass = __ruby__.getClassFromPath("MyRubyModule::MyNamespacedRubyClass");
IRubyObject param = JavaUtil.convertJavaToRuby(__ruby__, "test string1");
IRubyObject robject = Helpers.invoke(__ruby__.getCurrentContext(), rclass, "new", param);
System.out.println(Helpers.invoke(__ruby__.getCurrentContext(), robject, "str"));
// retrieve root class using getClassFromPath, instantiate object, call method
rclass = __ruby__.getClassFromPath("MyRootRubyClass");
param = JavaUtil.convertJavaToRuby(__ruby__, "test string2");
robject = Helpers.invoke(__ruby__.getCurrentContext(), rclass, "new", param);
System.out.println(Helpers.invoke(__ruby__.getCurrentContext(), robject, "str"));
// retrieve root class using getClass, instantiate object, call method
rclass = __ruby__.getClass("MyRootRubyClass");
param = JavaUtil.convertJavaToRuby(__ruby__, "test string3");
robject = Helpers.invoke(__ruby__.getCurrentContext(), rclass, "new", param);
System.out.println(Helpers.invoke(__ruby__.getCurrentContext(), robject, "str"));
}
}
module MyRubyModule
class MyNamespacedRubyClass
attr_reader :str
def initialize(str)
@str = str
end
end
end
class MyRootRubyClass
attr_reader :str
def initialize(str)
@str = str
end
end
javac -cp <path_to_jruby_jars>/jruby-core-1.7.4.jar CallJRuby.java
java -cp <path_to_jruby_jars>/*:. CallJRuby
@colinsurprenant
Copy link
Author

This is based on what jrubyc generates. This seems to work ok but I am wondering how this compares to all the other examples found on the JRuby wiki. Are there reasons to prefer or not this API usage style?

https://github.com/jruby/jruby/wiki/AccessingJRubyObjectInJava
https://github.com/jruby/jruby/wiki/JavaIntegration
https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment