Skip to content

Instantly share code, notes, and snippets.

@chrishunt
Created August 4, 2012 04:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrishunt/3254579 to your computer and use it in GitHub Desktop.
Save chrishunt/3254579 to your computer and use it in GitHub Desktop.
Ruby on Clojure

Ruby on Clojure

Note: Remove example deps from the local mvn cache so they need to be installed for the demo

$ rm -r ~/.m2/repository/{com/steelcity, jruby}

First, create your amazing Ruby library that you'd like to use in Clojure. We must require 'java' and we must specify a java package because the default package cannot be imported into our Clojure project.

$ vi person.rb
require 'java'
java_package 'com.steelcity'

class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def talk
    puts "Hello! My name is #{name}"
  end
end

Next, use JRuby to compile and package your Ruby library into a Java jar.

$ rvm jruby-1.6.7
$ jrubyc --javac person.rb
$ jar -cf person.jar com/steelcity/person.class

Since our new person.jar depends on JRuby, we'll copy the JRuby library from our rvm installation into our project for use later in Clojure.

$ which jruby
/Users/c/.rvm/rubies/jruby-1.6.7/bin/jruby

$ cp /Users/c/.rvm/rubies/jruby-1.6.7/lib/jruby.jar .

It's time to start using Clojure, so get things installed and create a new leiningen project.

$ brew install clojure
$ brew install leiningen
$ lein new ruby

Add both JRuby and our newly created person.jar as project dependencies.

$ cd ruby
$ vi project.clj
:dependencies [[org.clojure/clojure "1.3.0"]
               [jruby "1.6.7"]
               [com.steelcity/person "1.0.0"]])

We can now ask Leiningen to install our dependancies for us automatically, but since they're on our local machine and not the public maven repository, it doesn't know where to look for them. Luckily lein deps tells us how to get them installed.

$ lein deps

...
mvn install:install-file -DgroupId=com.steelcity -DartifactId=person -Dversion=1.0.0 -Dpackaging=jar -Dfile=/path/to/file
mvn install:install-file -DgroupId=jruby -DartifactId=jruby -Dversion=1.6.7 -Dpackaging=jar -Dfile=/path/to/file

Install both jruby-1.6.7.jar and person-1.0.0.jar using the provided commands.

$ mvn install:install-file -DgroupId=com.steelcity -DartifactId=person -Dversion=1.0.0 -Dpackaging=jar -Dfile=../person.jar
$ mvn install:install-file -DgroupId=jruby -DartifactId=jruby -Dversion=1.6.7 -Dpackaging=jar -Dfile=../jruby.jar
$ lein deps

We will now find our dependencies in our project directory under /lib

$ ls lib
clojure-1.3.0.jar jruby-1.6.7.jar   com.steelcity.person-1.0.0.jar

All done! Open a Clojure repl and load up your Ruby library.

$ lein repl
=> (import com.steelcity.Person)
=> (.talk (new Person "Doug"))
Hello! My name is Doug.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment