Executing a Ruby script from Java using JRuby results in 'LoadError: no such file to load ...'

Executing a Ruby script from Java using JRuby results in 'LoadError: no such file to load ...'

我想使用 JRuby(Linux Mint)从 Java 执行一个 Ruby 脚本。我可以通过调用 ruby script.rb 从终端成功执行脚本。但是,该脚本包含一个 require,当尝试使用 JRuby:

从 Java 执行它时会导致 "no such file to load" 异常
package com.company;

import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.PathType;
import org.jruby.embed.ScriptingContainer;

public class Main
{
    public static void main(String[] args)
    {
        ScriptingContainer ruby;
        ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);        
        Object result = ruby.runScriptlet(PathType.ABSOLUTE, "/home/user/Scripts/script.rb");
    }
}

问题似乎出在 script.rbrequire ... 部分,因为此代码适用于例如一个只显示文本的简单脚本。

该脚本使用 WinRb,一个用于 Windows 远程管理的 Ruby 库。 script.rb:

require 'winrm'

endpoint = 'http://somehost.domain.org:5985/wsman'
krb5_realm = 'DOMAIN.ORG'
command = 'hostname'

winrm = WinRM::WinRMWebService.new(endpoint, :kerberos, :realm => krb5_realm)

winrm.cmd(command) do |stdout, stderr|
  STDOUT.print stdout
  STDERR.print stderr
end

当我 运行 Java 代码时,我得到这个异常:

LoadError: no such file to load -- winrm
  require at org/jruby/RubyKernel.java:940
    <top> at /home/user/Scripts/script.rb:5
Exception in thread "main" org.jruby.embed.EvalFailedException: 
(LoadError) no such file to load -- winrm

这是我尝试过的:

  1. require 'rubygems' 添加到脚本的顶部。这只会将例外更改为 LoadError: no such file to load -- rubygems
  2. 指定完整路径:require '/var/lib/gems/1.9.1/gems/winrm-1.3.3/lib/winrm'。而不是原来的异常,在 运行 时间我现在得到:LoadError: no such file to load -- date require at org/jruby/RubyKernel.java:940

其他:

$ ruby -v
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]
$ jruby -v
jruby 9.0.0.0 (2.2.2) 2015-07-21 e10ec96 Java HotSpot(TM) 64-Bit Server VM 25.45-b02

如何让 JRuby 成功执行此脚本?

解决方法是:

jruby -S gem install winrm