Calling Clojure From JRuby

Clojure is a new functional programming language based on Lisp, running on the JVM. Even though Clojure is only a year old, there’s already a book being written about it.

Since this is a Ruby site, and Rails is still the best framework for web-apps regardless of language, I’ll demonstrate how to call Clojure functions from a JRuby Rails-app.

First an introduction to Clojure:

Clojure is an exciting language for four reasons. First, even though it’s a new language, there’s a vast amount of available libraries since it’s written for the JVM. Also, Clojure is not interpreted – it compiles functions directly to JVM bytecode, which means that it’s very fast. Thirdly, one of the goals of Clojure is to bring parallel programming to the masses, by supplying abstractions such as persistent datastructures (immutable, so they can be shared between threads), software transactional memory, and agents.

Finally, Clojure is a kind of Lisp, which means that you’ve got the power of macros. Macros are functions that run at compile time, and that return code, not data. Ruby makes generating code possible, but Lisp (and by extension Clojure) makes it easy, also removing the runtime performance penalty.

To compile this, Clojure will want to write the generated class files to the location defined in the *compile-path* global variable. In the REPL, it’s set to ‘classes’, in scripts it’s not set at all. If you’re in a directory with Blog.clj in nl/rubyenrails, and there’s a directory “classes”, you can compile the file from the REPL:

Now we can finally call our code. Simply require the jar file we’ve created. All Java classes are in the Java module – within the Java module, Java package names are converted to (capitalized) module names.

If you’ve made it this far, congratulations! You’ve now combined an hugely practical webframework with a incredibly powerful language running in the same enterprise-proof super-fast VM. The world lies at your feet.