JRuby on Rails:在Rails应用程序中使用自定义Java类 [英] JRuby on Rails: Using custom Java classes in your Rails app

查看:67
本文介绍了JRuby on Rails:在Rails应用程序中使用自定义Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用JRuby on Rails,并且绝对喜欢它.我知道如何在Rails应用程序中使用Java API中的当前类,但是如果我想创建一个用纯Java代码编写的新自定义类,我将如何在Rails应用程序中使用它?

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?

例如,假设我创建了Dog.java:

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

class Dog {
  private String name;

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

  public String getName() {
    return name;
  }
}

如何在Rails应用程序中创建一个新的Dog对象(Dog.new)?我需要将Dog.java或Dog.class文件放在某个位置,然后调用某种形式的导入"以将其导入到我的Rails应用程序中.我不知道这应该放在目录结构中的什么地方,也不知道我应该告诉我的应用程序如何包括它.

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. 编译类.

  1. Compile the class.

mkdir classes
javac -d classes src/Dog.java

  • 在您的Rails应用程序(例如初始化程序)的类路径中添加classes.

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

  • 导入课程.

  • Import the class.

    java_import Java::Dog
    

  • 如果要使用Warbler制作Rails应用程序的war文件,还可以使用config/warble.rb中的config.dirs选项将classes目录添加到war文件中,并且Dog类可以在不使用的情况下使用由于Java约定必须将WEB-INF/class添加到Java Web应用程序的类路径中,因此必须添加到$CLASSPATH.

    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.

    这篇关于JRuby on Rails:在Rails应用程序中使用自定义Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆