我很简单地需要在 Clojure 中使用 Ruby 类。复杂的因素是该类是在 gem 中提供的。最佳方法是按照以下行设置我的 Leiningein 项目文件:
(project foo ""
...
:dependencies [[clojure ...]
[jruby ... ]])
同样,我更愿意简单地将 gem 及其依赖项检查到本地 repo 目录中。因此,根据我的理想用法,将是:
(ns bar.baz
(require [jruby.something :as jruby])
(def obj (jruby/CreateAnInstance "TheGemClass"))
(def result (jruby/CallAMethod obj "method_name" some args))
谢谢。
最佳答案
这是获取 hello-world
gem 的简短步骤列表使用 JRuby 和 Clojure 以及一些引用资料运行。事实上,这些步骤只是一个简短的草图,说明如何将引用资料中的 Material 组合在一起(以及一些 project.clj
条目)。第一个引用,Haml on Clojure Web App在 Yoko Harada (@yokolet's) 的博客上,实际上使用了一种略微不同的方式来调用 JRuby,但包含了关于如何编写 require("...")
行以用于 JRuby 和类路径上的 gem 。
将
[org.jruby/jruby-complete "1.6.7.2"]
添加到您的:dependencies
并让 Leiningen 获取依赖项。在项目根目录中创建一个
gems
目录,并将其添加到project.clj
中的:resource-paths
这需要莱宁根 2. 查看 Leiningen source以获得正确的格式。说
# 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
在项目根目录中。
使用
GEM_HOME
和GEM_PATH
设置启动您选择的 REPL 服务。 (我用lein2 swank
对此进行了测试。)在 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)))
查看
nil
返回值,以及打印到 REPL 服务已启动的终端的几行。
引用资料:
- Haml on Clojure Web App在原田洋子 (@yokolet) 的博客上
- JRuby 1.1.6: Gems-in-a-jar在 Nick Sieger 的博客上
- DirectJRubyEmbedding在 Project Kenai 的 JRuby Wiki 上
- consuming gems from jruby-complete在这里(注意评论)
关于ruby - 使用 Clojure 的 gem 中提供的 JRuby 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12073844/