Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Wednesday, July 4, 2007

Use Your Favorite Ruby Library in Java

For QuickDeck we wanted to support Textile style editing, but we weren't able to find a great Java library to do it. I've been using RedCloth for my Ruby work - why not use that? Along comes Spring's built-in JRuby support to rock my world.
Here's the entirety of the process for integrating:

Add the JRuby jar


We're using Maven 2, so this just means adding a dependency like so:

<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby</artifactId>
<version>1.0</version>
</dependency>

Define the interface to implement



public interface TextileEngine {
String textileToHtml(String textile);
}

Create a JRuby script to integrate


This is a little singleton that adapts the RedCloth library to my interface.

require 'redcloth'

class RedClothTextileEngine
def textileToHtml(textile)
RedCloth.new(textile).to_html.to_s
end
end
RedClothTextileEngine.new

Put it in your Spring file



<lang:jruby id="textileEngine" script-interfaces="TextileEngine">
<lang:inline-script>
require 'redcloth'

class RedClothTextileEngine
def textileToHtml(textile)
RedCloth.new(textile).to_html.to_s
end
end
RedClothTextileEngine.new
</lang:inline-script>
</lang:jruby>

I decided to inline it because it's so short, you can also do something like this:

<lang:jruby id="textileEngine" script-source="classpath:redcloth_integration.rb" script-interfaces="TextileEngine"/&qt;

Use it!


We're using wicket-spring-annot, so just throw something like this in our Wicket components:

@SpringBean
private transient TextileEngine formatter;

And we've got Textile formatting courtesy of RedCloth and JRuby. Snap!

Footnote - the sort of ugly underbelly


The one ugly part of this was that I had to copy the redcloth.rb file into my project. It would have been a lot nicer to do something like this in my ruby script:

require 'rubygems'
gem 'RedCloth'
require 'redcloth'

but I don't want to require a separate JRuby install with rubygems, etc. Feel free to enlighten me on how to do this better!

google analytics tracking