ITコンサルの日常

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

Kernelモジュールにメソッド追加&二つの方法で呼び出し

Ruby#evalScriptletでKernelモジュールにメソッドを追加しておいてから、

  • Ruby#evalScriptletでメソッドを呼び出す
  • Ruby#getModule#callMethodでメソッドを呼び出す

の二つの方法を試してみる。

import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyString;
import org.jruby.runtime.builtin.IRubyObject;

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

		// Kernelモジュールにメソッドを追加
		String scriptlet = "module Kernel\n  def hoge(str)\n    'hoge: ' + str\n  end\nend\n";
		runtime.evalScriptlet(scriptlet);

		// testメソッドを呼んで、戻り値を取得する
		IRubyObject obj = runtime.evalScriptlet("hoge('from evalScriptlet')");
		System.out.println(obj.getClass().getName());
		System.out.println(obj);

		// Kernelモジュールを取得
		RubyModule rubyModule = runtime.getModule("Kernel");
		RubyString param = runtime.newString("from runtime.getModule");
		IRubyObject obj2 = rubyModule.callMethod(runtime.getCurrentContext(), "hoge", param);
		System.out.println(obj2.getClass().getName());
		System.out.println(obj2);
	}
}

結果はこう。

org.jruby.RubyString
hoge: from evalScriptlet
org.jruby.RubyString
hoge: from runtime.getModule

後者の方法であれば、引数をscriptletの文字列として組み立てなくてもできますね。