Java Code Examples for org.jruby.Ruby#evalScriptlet()

The following examples show how to use org.jruby.Ruby#evalScriptlet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RubyScript.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
protected Callable<Ruby> getInitRuby(final Writer out, final Writer err) {
    return new Callable<Ruby>() {
        @Override
        public Ruby call() throws Exception {
            RubyInstanceConfig config = new RubyInstanceConfig();
            config.setCompileMode(CompileMode.OFF);
            List<String> loadPaths = new ArrayList<String>();
            setModule(loadPaths);
            String appRubyPath = System.getProperty(PROP_APPLICATION_RUBYPATH);
            if (appRubyPath != null) {
                StringTokenizer tok = new StringTokenizer(appRubyPath, ";");
                while (tok.hasMoreTokens()) {
                    loadPaths.add(tok.nextToken().replace('/', File.separatorChar));
                }
            }
            config.setOutput(new PrintStream(new WriterOutputStream(out)));
            config.setError(new PrintStream(new WriterOutputStream(err)));
            Ruby interpreter = JavaEmbedUtils.initialize(loadPaths, config);
            interpreter.evalScriptlet("require 'selenium/webdriver'");
            interpreter.evalScriptlet("require 'marathon/results'");
            interpreter.evalScriptlet("require 'marathon/playback-" + framework + "'");
            return interpreter;
        }
    };
}
 
Example 2
Source File: RubyScriptTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@Test(enabled = false)
public void resultsCapturesJavaError() throws Exception {
    RubyScript script = new RubyScript(out, err, converToCode(SCRIPT_CONTENTS_ERROR_FROM_JAVA),
            new File(System.getProperty(Constants.PROP_PROJECT_DIR), "dummyfile.rb").getAbsolutePath(), false, null,
            Constants.FRAMEWORK_SWING);
    script.setDriverURL("");
    Ruby interpreter = script.getInterpreter();
    assertTrue("Collector not defined", interpreter.isClassDefined("Collector"));
    RubyClass collectorClass = interpreter.getClass("Collector");
    IRubyObject presult = JavaEmbedUtils.javaToRuby(interpreter, result);
    IRubyObject collector = collectorClass.newInstance(interpreter.getCurrentContext(), new IRubyObject[0], new Block(null));
    IRubyObject rubyObject = interpreter.evalScriptlet("proc { my_function }");
    try {
        collector.callMethod(interpreter.getCurrentContext(), "callprotected", new IRubyObject[] { rubyObject, presult });
    } catch (Throwable t) {

    }
    assertEquals(1, result.failureCount());
    Failure[] failures = result.failures();
    assertTrue("Should end with TestRubyScript.java. but has " + failures[0].getTraceback()[0].fileName,
            failures[0].getTraceback()[0].fileName.endsWith("TestRubyScript.java"));
    assertEquals("throwError", failures[0].getTraceback()[0].functionName);
}
 
Example 3
Source File: JRubyScriptUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new JRuby-scripted object from the given script source.
 * @param scriptSource the script source text
 * @param interfaces the interfaces that the scripted Java object is to implement
 * @param classLoader the {@link ClassLoader} to create the script proxy with
 * @return the scripted Java object
 * @throws JumpException in case of JRuby parsing failure
 */
public static Object createJRubyObject(String scriptSource, Class<?>[] interfaces, ClassLoader classLoader) {
	Ruby ruby = initializeRuntime();

	Node scriptRootNode = ruby.parseEval(scriptSource, "", null, 0);
       IRubyObject rubyObject = ruby.runNormally(scriptRootNode);

	if (rubyObject instanceof RubyNil) {
		String className = findClassName(scriptRootNode);
		rubyObject = ruby.evalScriptlet("\n" + className + ".new");
	}
	// still null?
	if (rubyObject instanceof RubyNil) {
		throw new IllegalStateException("Compilation of JRuby script returned RubyNil: " + rubyObject);
	}

	return Proxy.newProxyInstance(classLoader, interfaces, new RubyObjectInvocationHandler(rubyObject, ruby));
}
 
Example 4
Source File: RubyConsole.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
private void run(final Ruby runtime) {
    Thread t2 = new Thread() {
        public void run() {
            try {
                InputStream is = getClass().getResourceAsStream("/console_irb.rb");

                ByteArrayOutputStream ba = new ByteArrayOutputStream();
                int r;
                while ((r = is.read()) >= 0)
                    ba.write(r);
                is.close();

                //runtime
                //	.evalScriptlet("require 'irb'\n require 'irb/completion'\n IRB.start(__FILE__)\n");
                runtime.evalScriptlet(new String(ba.toByteArray()));
                //run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t2.start();
}
 
Example 5
Source File: JRubyScriptUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new JRuby-scripted object from the given script source.
 * @param scriptSource the script source text
 * @param interfaces the interfaces that the scripted Java object is to implement
 * @param classLoader the {@link ClassLoader} to create the script proxy with
 * @return the scripted Java object
 * @throws JumpException in case of JRuby parsing failure
 */
public static Object createJRubyObject(String scriptSource, Class<?>[] interfaces, ClassLoader classLoader) {
	Ruby ruby = initializeRuntime();

	Node scriptRootNode = ruby.parseEval(scriptSource, "", null, 0);
       IRubyObject rubyObject = ruby.runNormally(scriptRootNode);

	if (rubyObject instanceof RubyNil) {
		String className = findClassName(scriptRootNode);
		rubyObject = ruby.evalScriptlet("\n" + className + ".new");
	}
	// still null?
	if (rubyObject instanceof RubyNil) {
		throw new IllegalStateException("Compilation of JRuby script returned RubyNil: " + rubyObject);
	}

	return Proxy.newProxyInstance(classLoader, interfaces, new RubyObjectInvocationHandler(rubyObject, ruby));
}
 
Example 6
Source File: JRubyRackInputTest.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
@Test public void shouldWrapJavaIOExceptions() throws Exception {
  Ruby ruby = Ruby.newInstance();
  RackInput rackInput = mock(RackInput.class);
  when(rackInput.read(null)).thenThrow(new IOException("fake"));

  JRubyRackInput subject = new JRubyRackInput(ruby, rackInput);
  GlobalVariables globalVariables = ruby.getGlobalVariables();
  globalVariables.set("$rack_input", subject);

  IRubyObject result =
      ruby.evalScriptlet(
          "begin; $rack_input.read; rescue IOError => e; \"rescued #{e.message}\"; end");
  assertThat(result.asJavaString()).isEqualTo("rescued fake");
}
 
Example 7
Source File: MarathonRuby.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
public ContextAccessor(IRubyObject o) {
    this.o = o;
    Ruby runtime = o.getRuntime();
    marathon = runtime.evalScriptlet("$marathon");
}
 
Example 8
Source File: RubyUtils.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
public static void requireLibrary(Ruby rubyRuntime, String require) {
    rubyRuntime.evalScriptlet(String.format("require '%s'", require));
}
 
Example 9
Source File: RubyUtils.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
public static void loadRubyClass(Ruby rubyRuntime, InputStream rubyClassDefinition) {
    String script = IOUtils.readFull(rubyClassDefinition);
    rubyRuntime.evalScriptlet(script);
}
 
Example 10
Source File: RubyUtils.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
public static final void setGlobalVariable(Ruby rubyRuntime, String variableName, Object variableValue) {
    String script = String.format("$%s = %s", variableName, variableValue);
    rubyRuntime.evalScriptlet(script);
}