Skip to content

Instantly share code, notes, and snippets.

@shimarin
Created March 17, 2009 03:54
Show Gist options
  • Save shimarin/80274 to your computer and use it in GitHub Desktop.
Save shimarin/80274 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyString;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callback.Callback;
/**
* 再現環境:
* jruby.jar (1.0.3)
* backport-util-concurrent.jar
* asm-2.2.3.jar
* @author shimarin
*/
public class JRubyScopeTest {
public static void main(String[] args) {
Ruby runtime = JavaEmbedUtils.initialize(new ArrayList<String>());
// class MyClass ... end
RubyClass myClass = runtime.defineClass("MyClass",
runtime.getObject(), runtime.getObject().getAllocator());
// def hoge
myClass.defineMethod("hoge", new Callback() {
public IRubyObject execute(IRubyObject self, IRubyObject[] args, Block block) {
ThreadContext context = self.getRuntime().getCurrentContext();
// self.eval (*args)
return self.callMethod(context, "eval", args, block);
}
public Arity getArity() {
return Arity.ONE_REQUIRED;
}
});
System.out.println("Java版 Rubyクラス");
callHogeTwice(runtime, myClass);
runtime.evalScript("class MyClass2; def hoge(expr); eval(expr); end; end");
myClass = runtime.getClass("MyClass2");
System.out.println("Ruby版 Rubyクラス");
callHogeTwice(runtime, myClass);
}
private static void callHogeTwice(Ruby runtime, RubyClass clazz)
{
// myObj = MyClass.new
IRubyObject myObject = clazz.allocate();
// myObj.hoge("a=1")
myObject.callMethod(runtime.getCurrentContext(),
"hoge", RubyString.newUnicodeString(runtime, "a=1"));
// myObj = MyClass.new
myObject = clazz.allocate();
// myObj.hoge("p a")
myObject.callMethod(runtime.getCurrentContext(),
"hoge", RubyString.newUnicodeString(runtime, "p a"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment