RubyNoMethodError - 从Java调用ruby方法

时间:2012-07-12 18:09:23

标签: java ruby jruby

我有这个红宝石课:

require 'stringio'
require 'hirb'

class Engine
  def initialize()
    @binding = Kernel.binding
  end
  def run(code)
    # run something
    stdout_id = $stdout.to_i
    $stdout = StringIO.new
    cmd = <<-EOF
    $SAFE = 3
    $stdout = StringIO.new
    begin
      #{code}
    end
    EOF
    begin
      result = Thread.new { Kernel.eval(cmd, @binding) }.value
    rescue SecurityError
      return "illegal"
    rescue Exception => e
      return e
    ensure
      output = get_stdout
      $stdout = IO.new(stdout_id)
    end

    return output
  end

   private
   def get_stdout
     raise TypeError, "$stdout is a #{$stdout.class}" unless $stdout.is_a? StringIO
     $stdout.rewind
     $stdout.read
   end
end

“run”方法应该调用IRB的函数并捕获输出(字符串格式)。 我想从Java类调用此函数,但它无法找到IRB方法,即使它们被加载(需要'hirb')。 我的java类看起来像这样:

public class MyClass {
  private final static String jrubyhome = "/usr/lib/jruby/";
  private String rubySources;
  private String hirbSource;
  private String myEngine;
  private boolean loaded = false;

  private void loadPaths() {
    String userDir;

    userDir = System.getProperty("user.dir");
    rubySources = userDir + "/../ruby";
    hirbSource = userDir + "/hirb.rb";
    myEngine = rubySources + "/engine.rb";

    System.setProperty("jruby.home", jrubyhome);
    System.setProperty("org.jruby.embed.class.path", rubySources+":"+hirbSource);
    System.setProperty("hbase.ruby.sources", rubySources+":"+hirbSource);
  }

  private String commandResponse(String command) 
     throws FileNotFoundException
  { 
    String response;

    loadPaths();

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    ScriptingContainer container = new ScriptingContainer();

    Reader reader = new FileReader(myEngine);

    try {
      Object receiver = engine.eval(reader);
      String method = "run";
      Object ob  = container.callMethod(receiver,method,command);
      response = ob.getClass().toString();

      return response;
    } catch (ScriptException e) {
      System.out.println("exception");
    } 

    return "FAILED";
  }

  public static void main(String args[]) 
    throws IOException {
     MyClass my = new MyClass();
     System.out.println(my.commandResponse(args[0]));
  }  
}

你知道可能是什么问题吗?

[EDITED] 扩展内核模块并添加了有效的命令。

0 个答案:

没有答案