I try to call a Ruby method from Java
test_a.rb:
module Test
def Test.Test_1
stmt = "Test 1"
stmt
end
end
test.rb which includes the test_a.rb file
require_relative "./test/test_a.rb"
Java-Code
package com.example;
import java.util.ArrayList;
import org.jruby.embed.LocalContextScope;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.PathType;
import org.jruby.embed.ScriptingContainer;
public class test_ruby {
public static void main(String[] args) {
try {
ScriptingContainer jruby = new ScriptingContainer(LocalContextScope.THREADSAFE, LocalVariableBehavior.GLOBAL);
ArrayList<String> loadPath = new ArrayList<>();
loadPath.add("C:\\Users\\nikol\\Downloads\\starter\\ruby\\base");
jruby.setLoadPaths(loadPath);
System.out.println("Load Files");
jruby.runScriptlet(PathType.RELATIVE, "ruby\\\\base\\test\\lib\\test.rb");
String returnValue = jruby.runRubyMethod(String.class, null, "Test.Test_1");
System.out.println(returnValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The only output a managed is an error
Load Files
org.jruby.embed.InvokeFailedException: org.jruby.exceptions.NoMethodError: (NoMethodError) undefined method `Test.Test_1' for nil:NilClass
at org.jruby.embed.internal.EmbedRubyObjectAdapterImpl.doInvokeMethod(EmbedRubyObjectAdapterImpl.java:251)
at org.jruby.embed.internal.EmbedRubyObjectAdapterImpl.runRubyMethod(EmbedRubyObjectAdapterImpl.java:198)
at org.jruby.embed.ScriptingContainer.runRubyMethod(ScriptingContainer.java:1579)
at com.example.test_ruby.main(test_ruby.java:19)
Caused by: org.jruby.exceptions.NoMethodError: (NoMethodError) undefined method `Test.Test_1' for nil:NilClass
What is the correct way, to call this one method from Java?
I converted Test.Test_1 into a class, like all other examples. That worked for me.