Home > Java > JRuby using ScriptEngine, invoking methods, passing args

JRuby using ScriptEngine, invoking methods, passing args

Doing the same job with JRuby was, if anything, even easier than getting Jython up and running. Download jar, classpath it, run up a couple of units to test POC and then a quick and dirty Hello World:

   ScriptEngine engine = new ScriptEngineManager().getEngineByName("jruby");
    String f = "puts 'JRuby says hello world' " ;
        try {
            engine.eval(f);
        } catch (ScriptException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

No indentation issues to concern myself with, and because JRuby in most cases is agnostic about double or single quotes for String representations, no escaping either. Now I want to play with some of my mixins and classes to see what happens. First up in my list of concerns is that most of my Ruby classes were written back in the day when mastodons walked the earth, when the command line interface was at the cutting edge of GUI design, and gems were rare and precious commodities. By a flickering candle’s light I crafted a cunning set of .rb modules to give me access to a number of utilities, one of which was a toolset for doing some basic math stuff which ruby lacked at the time. Now it’s probably all plug and play and not only will it do the math for you, it’ll probably make you tea and hand around the biscuits whilst doing so. Let’s consider the following power method which I’ve isolated from its friends and loved ones and put into solitary in a new file called testpow.rb.

# raise a number to power
def power( a, pow )
ctr = 1
b = a
  while ctr < pow
    b = a * b
    ctr += 1
  end
return b
end

We have two issues to deal with here. We need to call the method and also pass arguments to the method via the ScriptEngine. The way this is done is with the Invocable interface (the relevant JavaDoc is here).

Now all we need to do to make use of this method is something not a million light years removed from this:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("jruby");
String pathToRubyScripts = "X:/anon/productionScripts/"; // obviously make this appropriate to your .rb file locations
    FileReader fr = null;
    Invocable inv = null;
        try {
            fr = new FileReader(pathToRubyScripts + "testpow.rb");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
              engine.eval(fr);
               inv = (Invocable) engine;
            try {
                long lg = (Long) inv.invokeFunction("power", 10,3); //invoke(String,Object args)
                System.out.println("Answer: " + lg);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ScriptException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

Quietly I’m impressed with just how easy it is to implement scripting in Java.

About these ads
Categories: Java Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: