使用Clojure的gem中提供的JRuby类

fog*_*gus 10 ruby gem interop jruby clojure

我很简单地需要在Clojure中使用Ruby类.复杂的因素是该类是在宝石中提供的.最佳方法是按照以下方式设置我的Leiningein项目文件:

(project foo ""
  ...
  :dependencies [[clojure ...]
                 [jruby ...  ]])
Run Code Online (Sandbox Code Playgroud)

同样,我更愿意只检查gem及其依赖项到本地repo目录中.因此,从我理想的用法是:

(ns bar.baz
  (require [jruby.something :as jruby])

(def obj (jruby/CreateAnInstance "TheGemClass"))

(def result (jruby/CallAMethod obj "method_name" some args))
Run Code Online (Sandbox Code Playgroud)

谢谢.

Mic*_*zyk 10

下面是使用JRuby和Clojure以及一些参考资料来运行hello-worldgem的简短步骤列表.实际上,这些步骤只是简单描述了参考文献中的材料如何组合在一起(有些project.clj条目).第一个参考资料,在Yoko Harada(@ yokolet's)博客上使用Clojure Web App上的Haml,实际上使用了一种稍微不同的方式来调用JRuby,但包括如何require("...")在类路径上编写与JRuby和gems一起使用的行的关键注释.

  1. 添加[org.jruby/jruby-complete "1.6.7.2"]到您的:dependenciesLeiningen并获取依赖项.

  2. 创建一个gems项目根目录下,并将其添加到:resource-paths您的project.clj这个要求Leiningen 2.见Leiningen来源为正确的格式.

  3. # see reference 4
    GEM_HOME=gems GEM_PATH=gems java -jar ~/.m2/repository/org/jruby/jruby-complete/1.6.7.2/jruby-complete-1.6.7.2.jar -S gem install hello-world
    
    Run Code Online (Sandbox Code Playgroud)

    在项目根目录中.

  4. 启动您的选项的REPL服务GEM_HOMEGEM_PATH如上设置.(我测试了这个lein2 swank.)

  5. 在REPL中说出以下内容:

    ;;; see reference 2, first snippet
    (let [runtime (JavaEmbedUtils/initialize (list))
          evaler  (JavaEmbedUtils/newRuntimeAdapter)]
      (doseq [ruby-expr ["require('rubygems')"
                         "require('gems/hello-world-1.2.0/lib/hello-world')"]]
        (.eval evaler runtime ruby-expr)))
    
    Run Code Online (Sandbox Code Playgroud)
  6. 看看nil返回值,以及打印到REPL服务的终端的几行.

参考文献:

  1. 在Yoko Harada(@ yokolet's)博客上的Clojure Web App上的Haml
  2. JRuby 1.1.6: Nick Sieger博客上的Gems-in-a-jar
  3. 在Kenai项目的JRuby Wiki上的DirectJRubyEmbedding
  4. 在这里消费来自jruby-complete的宝石(请注意评论)

  • 工作得很完美,谢谢.我需要做的唯一更改是在执行上述命令之前导入`JavaEmbedUtils`. (3认同)