Rack Servlet
Embed Rack applications in your Java service.
Written by Matthew Todd.
Today we’re releasing Rack Servlet, a small JRuby-backed servlet designed for embedding in your Java application.
Rack Servlet comes from our ongoing Minecart work to bring Ruby applications into Square’s sophisticated Java service container.
As compared with the other options for running Rack applications on the JVM, we think there’s a place for a small library like this: Kirk is a full Rack server, like Mongrel or Unicorn; Warbler builds WAR files; and jruby-rack, while amazing, has a less clear embedding story.
Embedding
To embed a Rack Servlet into your own application, first install rack-servlet and jruby-complete:
<dependency>
<groupId>com.squareup.rack</groupId>
<artifactId>rack-servlet</artifactId>
<version>${rack.servlet.version}</version>
</dependency>
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>
<version>${jruby.version}</version>
</dependency>
Then use JRuby to build your Rack application:
ScriptingContainer ruby **=** **new** **ScriptingContainer();**
String script **=** "lambda { |env| [200, {}, ['Hello, World!'] }"**;**
IRubyObject application **=** ruby**.**parse**(**script**).**run**();**
And wrap that application in the loving embrace of a RackServlet:
Servlet servlet **=** **new** **RackServlet(new** **JRubyRackApplication(**application**));**
From there, you’ll just need to install that servlet in your container. We’ve got a handful of examples in the repository to get you started — including integrations with Dropwizard, Guice Servlet, and straight-up Jetty.
Enjoy!
We’ve taken care with Rack Servlet both to keep its dependencies small, and to shape its API so that it’s even friendly to use from Ruby code. Keep an eye on the repository for further examples and integration support libraries in the coming days.
This post is part of a series, which highlights discoveries and insights found while integrating Ruby with our robust Java stack. Matthew Todd (@matthewtodd) | Twitter *The latest Tweets from Matthew Todd (@matthewtodd). Programmer, vegan, sometime runner. I work @square. Oakland…*twitter.com