Using Ruby gems in Java/Gradle projects with JRuby

Let’s have a quick look on how to reuse our Ruby code and gems in Java leveraging the awesome work of JRuby guys. What we need is Java, Gradle and JRuby installed and we are ready to rock.

I decided to try reusing my already made invoicing gem InvoicePrinter and see how much pain it would be to actually use a gem like that in a Java project instead of writing the same thing again in pure Java. For starters I installed Java, Gradle and JRuby. I installed JRuby with ruby-install via chruby (see my bold opinions on managing Ruby versions here):

And then created a new project with Gradle:

Since we will need to load our gems from somewhere let’s install them to a folder called rubygems and let’s create a JAR out of them:

We need to work with JARs in Java, but luckily JRuby can automatically find your gems for requires if you package a RubyGems tree like that in a JAR and compile them as other JARs in the project.

Now we are ready to implement our Java class with some embedded Ruby:

I am calling the project invoicing_automat and creating a file called with the following content:

The Ruby code itself is taken from the gem examples and we are just evaluating the Ruby code via JRuby ScriptEngineManager. Unfortunately Java lacks the Ruby’s HEREDOC syntax which makes the code looks kind of bad (there is an option to load the Ruby code from separate file of course).

Last thing missing is our Gradle config build.gradle in which we have to specify our compile dependencies:

We need JRuby package from Maven and our local JAR containing the gems we are requiring from file. Once updated let’s see the result:

In our project repository appeared a file called simple_invoice.pdf. Yay JRuby works! Mixing Ruby in Java and Java in Ruby is a promising approach and I will hopefully explore more of JRuby in foreseeable future.

Leave a comment

Your email address will not be published. Required fields are marked *