Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a JRuby CompiledScript in Java

Tags:

java

jruby

I have a Ruby script that I'd like to run at the startup of my Java program.

When you tell the ScriptEngine to evaluate the code for the first time, it takes a while. I'm under the impression that the reason it takes this long is because it first needs to compile the code, right?

I found that you can compile Ruby code, and then evaluate it later. The evaluation itself is fast - the compilation part is the slow one. Here I am compiling:

    jruby = new ScriptEngineManager().getEngineByName("jruby");

    Compilable compilingEngine = (Compilable)jruby;

    String code = "print 'HELLO!'";

    CompiledScript script;
    script = compilingEngine.compile(code);

This snippet is what takes a while. Later when you evaluate it, it is fine.

So of course, I was wondering if it would be possible to "save" this compiled code into a file, so in the future I can "load" it and just execute it without compiling again.

like image 252
Voldemort Avatar asked Feb 14 '23 00:02

Voldemort


1 Answers

As others have said, this is not possible with CompiledScript. However, with JRuby you have another option. You can use the command line tool jrubyc to compile a Ruby script to Java bytecode like so:

jrubyc <scriptname.rb>

This will produce a class file named scriptname.class. You can run this class from the command line as if it were a normal class with a main(String[] argv) method (note: the jruby runtime needs to be in the classpath) and you can of course load it into your application at runtime.

You can find more details on the output of jrubyc here: https://github.com/jruby/jruby/wiki/JRubyCompiler#methods-in-output-class-file

like image 190
Gary Tierney Avatar answered Feb 15 '23 13:02

Gary Tierney