简体   繁体   English

JRuby on Rails:在Rails应用程序中使用自定义Java类

[英]JRuby on Rails: Using custom Java classes in your Rails app

I just started with JRuby on Rails and absolutely love it. 我刚开始使用JRuby on Rails并且非常喜欢它。 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? 我知道如何在我的Rails应用程序中使用Java API中的当前类,但如果我想创建一个用纯Java代码编写的新自定义类,我怎样才能在我的Rails应用程序中使用它?

For example, let's say I created Dog.java: 例如,假设我创建了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? 我怎样才能在我的Rails应用程序中创建一个新的Dog对象(Dog.new)? 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. 我需要将Dog.java或Dog.class文件放在某处,然后调用某种形式的“import”将其导入我的Rails应用程序。 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. 我不知道这应该放在目录结构中,也不知道我应该在哪里以及如何告诉我的应用程序如何包含它。

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). classes添加到Rails应用程序中的类路径(例如,初始化程序)。

     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. 如果你想用Warbler制作你的Rails应用程序的war文件,你也可以使用config/warble.rbconfig.dirs选项将classes目录添加到war文件中,并且Dog类将可用而无需添加到$CLASSPATH因为Java约定将WEB-INF / classes添加到Java Web应用程序的类路径中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM