ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

JavaからFixturesを使ってみる

昨日のFixturesをRails外で使ってみるは、これの伏線なのでした。


で、JavaからJRubyを使ってRubyのライブラリを使う方法ですが、
色々やったところ、org.jruby.Ruby#evalScriptletってのを使うとできるようです。
org.jruby.runtime.load.LoadService#requireってのだと、うまく行きませんでした。。

import java.io.*;
import java.util.*;

import org.jruby.*;
import org.jruby.ast.*;
import org.jruby.runtime.*;
import org.jruby.runtime.builtin.*;

public class CallRuby
{
	public static void main(String[] args) throws Exception
	{
		Ruby runtime = Ruby.newInstance();

		BufferedReader br = new BufferedReader(new FileReader("hoge.rb"));
		StringBuffer sb = new StringBuffer();
		String str;
		while((str = br.readLine()) != null)
		{
			sb.append(str + "\n");
		}
		br.close();

		System.out.println(sb.toString());
		runtime.evalScriptlet(sb.toString());
	}
}

コンパイル

javac -classpath E:\jruby-1.1.4\lib\jruby.jar CallRuby.java

実行

java -Djruby.home=%JRUBY_HOME% -classpath %JRUBY_HOME%\lib\jruby.jar;. CallRuby

結果

insert
select all
1/test
2/hoge
3/hoge0
4/hoge1
5/hoge2
6/hoge3
7/hoge4
8/hoge5
9/hoge6
10/hoge7
11/hoge8
12/hoge9
delete
select all
finish