Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created December 3, 2010 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboyd/727585 to your computer and use it in GitHub Desktop.
Save cowboyd/727585 to your computer and use it in GitHub Desktop.
try to get a top-level constant
package foo;
import org.jruby.embed.ScriptingContainer;
import org.jruby.embed.LocalContextScope;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.internal.LocalContext;
public class Fooby {
public static void main(String[] args) {
ScriptingContainer ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
ruby.runScriptlet("class Foo;end");
System.out.println("ruby.get(\"Foo\") = " + ruby.get("Foo"));
System.out.println("ruby.runScriptlet(\"JRUBY_VERSION\") = " + ruby.runScriptlet("JRUBY_VERSION"));
}
}
/**output
ruby.get("Foo") = null
ruby.runScriptlet("JRUBY_VERSION") = 1.5.3
*/
@yokolet
Copy link

yokolet commented Dec 8, 2010

"Right way" is not only one. To me, this code looks doing right so far since this is just a class definition. Next would be how you can use defined class, "Foo." For example,

Object foo = ruby.get("Foo");  // got RubyClass
Object ifoo = ruby.callMethod(foo, "new", Object.class); // got RubyObject

Or, simply,

Object ifoo = ruby.runScriptlet("f = Foo.new"); // got RubyObject

The former one is a little bit better in terms of performance. The latter one should be merged to the class definition when performance matters.

BTW, did you get null from "ruby.get("Foo")" ? As far as I tried using master branch, I got RubyClass.

@cowboyd
Copy link
Author

cowboyd commented Dec 8, 2010

Yes, I got null. Is this in the released version?

@yokolet
Copy link

yokolet commented Dec 8, 2010

Ah..., no. I modified (improved) constant related implementation in master, I mean, 1.6.0.dev. Would you try this out using snapshot? As far as I remembered, that was September-ish work.

@cowboyd
Copy link
Author

cowboyd commented Dec 8, 2010

I'll take your word for it. In the mean time, we can just use runScriptlet('Foo') to get the constant reference which is totally fine.

@yokolet
Copy link

yokolet commented Dec 8, 2010

Sorry about that. runScriptlet('Foo') is a simple and steady way and works surely on both 1.5.x and 1.6.x. It is definitely a right way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment