Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JRuby on Rails: Using custom Java classes in your Rails app

I just started with JRuby on Rails and absolutely love it. I know how to use current classes within the Java API in my Rails app, but if I wanted to create a new custom class written in purely Java code, how would I be able to use it in my Rails app?

For example, let's say I created Dog.java:

class Dog {
  private String name;

  public Dog() {
    name = "Fido";
  }

  public String getName() {
    return name;
  }
}

How would I be able to create a new Dog object (Dog.new) in my Rails app? I need to put the Dog.java or Dog.class file somewhere, and then call some form of "import" to import it into my Rails app. I have no idea where this should go in the directory structure nor do I know where and how I should tell my app how to include it.

like image 437
Joel Andritsch Avatar asked Oct 12 '10 17:10

Joel Andritsch


1 Answers

You'll need a couple things.

  1. Compile the class.

    mkdir classes
    javac -d classes src/Dog.java
    
  2. Add classes to the classpath in your Rails application (an initializer for example).

    require 'java'
    $CLASSPATH << File.join(Rails.root, "classes")
    
  3. Import the class.

    java_import Java::Dog
    

If you want to make a war file of your Rails app with Warbler, you could also add the classes directory to the war file using the config.dirs option in config/warble.rb, and the Dog class will be available without having to add to $CLASSPATH because of the Java convention that WEB-INF/classes be added to the classpath in a Java web application.

like image 127
Nick Sieger Avatar answered Oct 22 '22 11:10

Nick Sieger