Skip to content

Instantly share code, notes, and snippets.

@chadselph
Created August 12, 2016 04:59
Show Gist options
  • Save chadselph/0be497f37b16f1b01009836686e3875c to your computer and use it in GitHub Desktop.
Save chadselph/0be497f37b16f1b01009836686e3875c to your computer and use it in GitHub Desktop.
JRuby instance_evals
import org.jruby.embed.ScriptingContainer;
public class RubyTest {
public static void main(String[] args) {
ScriptingContainer container = new ScriptingContainer();
// From a string
Object myclassString = container.runScriptlet("" +
"class MyClass\n" +
" def parse_stuff(body)\n" +
" instance_eval(body)\n" +
" end\n" +
"end\n" +
"MyClass.new");
container.callMethod(myclassString, "parse_stuff",
"Kernel.eval 'def abc() ::Kernel.puts 123 end'\n" +
"abc");
}
}
/*
Output:
NameError: undefined local variable or method `abc' for #<MyClass:0x7bac686b>
<eval> at (eval):2
*/
@chadselph
Copy link
Author

chadselph commented Aug 12, 2016

In irb...

irb(main):009:0> class MyClass
irb(main):010:1>  def parse_stuff(body)
irb(main):011:2>   instance_eval(body)
irb(main):012:2>   end
irb(main):013:1> end
=> nil
irb(main):014:0> m = MyClass.new
=> #<MyClass:0x007ff293903688>
irb(main):015:0> m.parse_stuff("::Kernel.eval('def foo; ::Kernel.puts 2; end');foo")
2
=> nil
irb(main):016:0>

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