问题
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.
回答1:
You'll need a couple things.
Compile the class.
mkdir classes javac -d classes src/Dog.java
Add
classes
to the classpath in your Rails application (an initializer for example).require 'java' $CLASSPATH << File.join(Rails.root, "classes")
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.
来源:https://stackoverflow.com/questions/3917358/jruby-on-rails-using-custom-java-classes-in-your-rails-app