Tuesday Mar 17, 2009

JRuby Fusion

I recently ported a medium-sized Java web application to Ruby on Rails. Overall it was a gratifying experience but I struggled with PDF generation, and specifically the limits of the Ruby PDF generator PDF::Writer and associated SimpleTable.

Actually PDF::Writer itself is fairly powerful but unfortunately SimpleTable lives up to its name by lacking many of the features found in other PDF generators.

My original Java app uses the awesome iText PDF generator which has extensive table support.

After fiddling with SimpleTable for a while, I gave up and wrote a simple bridge between my Rails app and my original Java PDF generation servlet. On the rails side I create a delimited string containing each record to be printed, and post that to the servlet with:

    http.post(path_to_servlet, delimited_string)

On the Java side I parse the InputStream to retrieve the values, and generate table cells using the iText APIs.

This is straightforward, but it bugs me having to maintain two codebases in two languages, and deploy two separate applications, one in an app server, to support PDF generation. It would be far preferable to access iText directly from Ruby.

Enter JRuby

So I installed JRuby on my S10 box, and entered these two commands (courtesy Charles Nutter):

  % gem install glassfish-gem-10.0-SNAPSHOT.gem
  % glassfish_rails myapp

And voila: my app is running inside Glassfish on JRuby. Wow - that was easy! I can get rid of my mongrels and manage everything from GlassFish. Even better, I can now call Java from within ruby:

setenv CLASSPATH itext.jar

require 'java'

include_class 'java.io.FileOutputStream'
include_class 'com.lowagie.text.Document'

document = Document.new(PageSize::A4.rotate(), 10, 10, 10, 10)
pdfFile = FileOutputStream.new("it_works.pdf")

writer = PdfWriter.getInstance(document, pdfFile)

table = PdfPTable.new(9)

This is the best of all worlds. Of course there are some downsides with this approach, such as inevitable impedance mismatches between Java and Ruby, code maintainability issues, etc. but this approach quickly and elegantly solved my original problem of not being able to access iText.

First impressions: JRuby Rocks.

About

john

Search

Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today