using a third party java class in your ruby script

JRuby facilitates the use of java classes in your ruby scripts. This is quite trivial when you are using the standard java classes that are shipped with the jdk and with the package names starting with, java, javax, com and org. For those classes you do not need to specify a jar file or anything, and it is just a matter of couple of lines. Following two lines show how to make a swing JFrame in Jruby.

JFrame = javax.swing.JFrame
frame = JFrame.new

But if you need to use a java class written by your self in your ruby script. Then you need some additional code lines. Assume that we need to use the following simple java class in our jruby script.

package package1;

public class Helloworld {
public String sayHello(){
return “hello”;
}
}

Then you need to export this java class as a jar file and store it in your file system.
Now it’s time to get back to ruby work. In JRuby you need to declare that you are going to use java in your ruby script. For that inserting the following line is vital.

include Java

Then you need to tell the JRuby interpreter the location of your java class. So if the jar file which contains th e java class, is stored at “/home/thilina/some/where/HelloWorld.jar” . Then add the following line.

require “/home/thilina/some/where/HelloWorld.jar”

Now you can repeat the same thing we did in our very first code segment ( creating a JFrame in Ruby)

HelloWorld = Java::package1.HelloWorld

Remember you need to adhere with the standard java naming convention here. In your java class, start your package name with a lowercase letter and a class name with an uppercase letter. This will avoid you from a lot of complains that JRuby interpreter will throw at you. Now the java class is available for your use.

helloWorldInstance = HelloWorld.new
puts helloWorldInstance.sayHello

If you are lucky enough, preceding lines will be resulted in printing “hello” in your screen.

Advertisements

About this entry