How to create a Ruby module in Java using JRuby?

In Ruby, I can have a module like:

module Greeter
  def greet
    print "Hello"
  end
end

And my class can get the method greetas follows:

class MyClass
  include Greeter
end

obj = MyClass.new
obj.greet

Now I would like to use my module Greeterimplemented in Java. I am using JRuby. I'm not sure how to create a Ruby module in Java (in such a way that I can fine include).

For a moment I want to make a Java interface. Including this in my Ruby class does not cause errors, but in fact it is not the same, since the modules seem to implement the methods, while the Java interface does not.

+4
source share
1 answer

, , Java.

( ), , .

Greeter:

import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

public class Greeter {

    @JRubyMethod
    public static void greet( ThreadContext context, IRubyObject self ) {
        System.out.printf("Hello from %s%n", self);
    }

}

GreeterService :

import org.jruby.Ruby;
import org.jruby.RubyModule;
import org.jruby.runtime.load.BasicLibraryService;

import java.io.IOException;

public class GreeterService implements BasicLibraryService {

    @Override
    public boolean basicLoad(final Ruby runtime) throws IOException {
        RubyModule greeter = runtime.defineModule(Greeter.class.getSimpleName());
        greeter.defineAnnotatedMethods(Greeter.class);

        return true;
    }

}

, , JRuby script:

require 'target/jruby-example.jar'
require 'greeter'

class MyClass
  include Greeter
end

obj = MyClass.new
obj.greet

jruby-example.jar , . , , . , Enumerable.

+6

All Articles