JSR 223 API のJRuby script engineを使うサンプルコード その2

Rubyスクリプトでは何かのライブラリを require 'net/http'のようにして参照することがありますが、実行時にはライブラリがどこにあるかを何かの方法で設定しなければいけません。JRubyでは基本的なライブラリ、例えば、jruby-1.0.2/lib/ruby/1.8以下やjruby-1.0.2/test以下にあるものの場合は何もしなくていいのですが、それ以外はクラスパスにセットするか、-Iオプションで指定するなどをします。JSR 223のJRuby engineを使っている場合はクラスパスで設定できますが、そればかりではなく、com.sun.script.jruby.loadpathというシステムプロパティでも設定できます。このようなプログラムを書いて、

import java.io.FileReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class TestEvaluation {

    public static void main(String[] args) {
        try {
            String loadPath = "/home/yoko/tools/jruby-1.0.2:/home/yoko/tools/jruby-1.0.2/lib/ruby/1.8";
            System.setProperty("com.sun.script.jruby.loadpath", loadPath);
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("jruby");
            String testname = "/home/yoko/tools/jruby-1.0.2/test/testKernel.rb";
            engine.put("ScriptEngine.FILENAME", testname);
            engine.eval(new FileReader(testname));
        } catch (Exception ex) {
            Logger.getLogger(TestEvaluation.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

実行すると、

kernel : .......................................................
                                                                                                                                                              • -
                                                                                                                                                              • -
Tests: 55. (Ok: 55; Failed: 0)

のようにテストの結果が表示されます。