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

限于喜欢 提交于 2019-12-10 13:23:12

问题


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.

  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.



来源:https://stackoverflow.com/questions/3917358/jruby-on-rails-using-custom-java-classes-in-your-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!