To define a ruby module, the java class doesn't have to inherit from RubyObject
and no object allocator is required.
@JRubyModule(name = "Protobuf")
public class RubyProtobuf {
public static void createProtobuf(Ruby runtime) {
RubyModule google = runtime.getOrCreateModule("Google");
RubyModule protobuf = google.defineModuleUnder("Protobuf");
protobuf.defineAnnotatedMethods(RubyProtobuf.class);
// To define constants that are integers
protobuf.defineAnnotatedConstants(RubyProtobuf.class);
// Define constant
protobuf.defineConstant("ACCEPTED", runtime.newFixnum(1));
}
@JRubyConstant
public final static int OK = 0;
}
To define method in module, the method has to be declared static
, the first two parameters are ThreadContext context
and IRubyObject recv
.
// JRubyMethod decides how the ruby world see the method, it has the following options:
// required, optional, rest, meta
@JRubyMethod(name = "count")
public static IRubyObject count(ThreadContext context, IRubyObject self, final Block block) {
Add meta=true
to @JRubyMethod(meta=true)
if the method is a module method.