(See Show Notes Below ↓)

comments powered by Disqus

Find a copy of the companion source code for this episode here:

https://github.com/upgradingdave/javajing/tree/master/ruby-from-java

In case you're viewing this in github, please find the Episode here:

http://javajing.com/2012/06/01/ruby-from-java.html

Steps to Run Ruby from Java

  • Include the jruby-complete-<version>.jar dependency on the classpath for your project. This is really all that's needed to run jruby code
  • Use BSF, JSR223 or jruby core to "embed" ruby inside java (run ruby from java). See the Jruby wiki for more.
  • Try using jruby-complete-<version>.jar to run a simple ruby script. This should fail because jruby-complete won't be able to find the sass gem.
    java -jar jruby-complete-1.6.7.jar -S sass_helper.rb
    
  • To use ruby gems from java, first package the gem into a jar file
    mkdir sass-gems
    java -jar jruby-complete-1.6.7.jar -S gem install -i ./sass-gems sass --no-rdoc --no-ri
    jar cf sass-gems.jar -C sass-gems .
    
  • Verify that the jar contains the correct gem directory structure.
    jar -tf sass-gems.jar | head
    
  • Now, the sasshelper.rb script should run successfully as long as it it can find the jar containing the sass gem
    java -jar jruby-complete-1.6.7.jar -S sass_helper.rb  # will still fail
    java -jar jruby-complete-1.6.7.jar -rsass-gems.jar -S sass_helper.rb
    
  • Publish the custom created jar to a repo so that we can use it as a maven dependency
    mvn deploy:deploy-file -DgroupId=com.upgradingdave -DartifactId=sass-gem -Dversion=3.1.17 -Dpackaging=jar -Dfile=sass-gems.jar -Durl=http://dev.upgradingdave.com/artifactory/ext-release-local -DrepositoryId=upgradingdave-release
    
  • Add com.upgradingdave:sass-gems:3.1.17 to pom and then test by calling sasshelp.rb from RubyExample.java main method
  • For convenience, use gem maven plugin to automatically retrieve gems as maven artifacts from torquebox rubygems maven proxy repository

Links

Embedding ruby inside java: https://github.com/jruby/jruby/wiki/RedBridge

Package gems into a jar: http://blog.nicksieger.com/articles/2009/01/10/jruby-1-1-6-gems-in-a-jar

Maven proxy that automatically converts ruby gems to maven dependencies: http://rubygems-proxy.torquebox.org/

Gem Maven Plugin http://blog.mkristian.tk/2010/08/managing-jruby-projects-with-maven.html

Ruby Version Manager (very convenient for installing and using jruby, along with other ruby implementations) https://rvm.io/