Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

Ruby tutorial



This tutorial explains how to load a Ruby script and use it from Java.

Overview

We will define a Script interface, and run a Ruby Script as a class which implements this interface from Java.

Define the Script interface

Our interface will be very simple[1]
It's the same as for the Groovy tutorial
. We will have the following definition for the interface.
      public interface Script {
        public int execute();
      }

Define the Ruby script wrapper

We will extend the RubyScriptWrapper in the Groovy language to define that our scripts implement our script interface. We will have the following simple class:
      public class RubyScriptWrapperImpl extends RubyScriptWrapper<Script> {
      }
With this definition, we have defined that our wrapper wrap scripts which implement the Script interface.

Getting the script proxy

In the basic usage, you will get a script proxy from the wrapper with ScriptWrapper.getScriptProxy(). The proxy you will get implements your Script interface, and you will be able yo use it exactly as any implementation of this interface.

Get a Script proxy

We will simply use the ScriptWrapper.getScriptProxy() method to get a proxy which will implement our interface:
       ScriptWrapper<Script> wrapper = new RubyScriptWrapper<Script>(){
      };

Use the scripting runtime

Suppose we have the following Ruby script:
      def execute
        return 10
      end
We will get the script and create the ScriptWrapper:
      File file = new File(<our script file>);
      Script script = wrapper.installScript(file);
And now we can run the method:
      int value = script.execute();
      // value is 10

Notes

  1. ^ It's the same as for the Groovy tutorial

Categories: tutorials

Copyright 2019-2020 Herve Girod. All Rights Reserved. Documentation and source under the BSD licence