org.jruby.Ruby Java Examples

The following examples show how to use org.jruby.Ruby. 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: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * setErrorWriter - based on ScriptContainer#setErrorWriter
 * 
 * @param ostream
 */
protected IRubyObject setErrorWriter(OutputStream ostream)
{
	Ruby runtime = getRuntime();
	IRubyObject oldValue = runtime.getObject().getConstant(STDERR_CONSTANT);

	if (ostream != null)
	{
		PrintStream pstream = new PrintStream(ostream);
		RubyIO io = new RubyIO(runtime, pstream);

		io.getOpenFile().getMainStream().setSync(true);
		setErrorWriter(io);
	}

	return oldValue;
}
 
Example #2
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
private static void handleFormatAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(Format.class)) {
        Format format = processor.getAnnotation(Format.class);
        switch (format.value()) {
            case CUSTOM:
                rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                        rubyRuntime.newSymbol("regexp"),
                        convertRegexp(rubyRuntime, format.regexp())
                });
            default:
                rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                        rubyRuntime.newSymbol("format"),
                        rubyRuntime.newSymbol(format.value().optionValue().substring(1))
                });
        }
    }
}
 
Example #3
Source File: RubySchema.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * This method registers the class with the given runtime.
 *
 * @param runtime an instance of the Ruby runtime
 * @return        a RubyClass object with metadata about the registered class
 */
public static RubyClass define(Ruby runtime) {
    RubyClass result = runtime.defineClass("Schema",runtime.getObject(), ALLOCATOR);

    result.kindOf = new RubyModule.KindOf() {
        public boolean isKindOf(IRubyObject obj, RubyModule type) {
            return obj instanceof RubySchema;
        }
    };

    result.includeModule(runtime.getEnumerable());

    result.defineAnnotatedMethods(RubySchema.class);

    return result;
}
 
Example #4
Source File: EditorContextContributor.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public void modifyContext(CommandElement command, CommandContext context)
{
	IEditorPart editor = this.getActiveEditor();

	if (editor != null && command != null)
	{
		Ruby runtime = command.getRuntime();

		if (runtime != null)
		{
			IRubyObject rubyInstance = ScriptUtils.instantiateClass(runtime, ScriptUtils.RUBLE_MODULE,
					EDITOR_RUBY_CLASS, JavaEmbedUtils.javaToRuby(runtime, editor));

			context.put(EDITOR_PROPERTY_NAME, rubyInstance);
		}
		else
		{
			context.put(EDITOR_PROPERTY_NAME, null);
		}
	}
}
 
Example #5
Source File: ModuleListTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public void checkForListArgs() throws Exception {
    ModuleList moduleList = new ModuleList(Ruby.newInstance(), "selection");
    Module top = moduleList.getTop();
    List<Module> modules = top.getChildren();
    assertEquals(1, modules.size());
    Module arrays = modules.get(0);
    assertEquals("arrays", arrays.getName());
    List<Function> functions = arrays.getFunctions();
    assertEquals(3, functions.size());
    Function selectOneFunction = functions.get(0);
    assertEquals("select_one", selectOneFunction.getName());
    List<Argument> arguments = selectOneFunction.getArguments();
    assertEquals(2, arguments.size());
    Argument arg = arguments.get(0);
    assertEquals("integers", arg.getName());
    assertNull(arg.getDefault());
    assertNotNull(arg.getDefaultList());
    arg = arguments.get(1);
    assertEquals("strings", arg.getName());
    assertNull(arg.getDefault(), arg.getDefault());
    assertNotNull(arg.getDefaultList());
}
 
Example #6
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 #7
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
@Override
public PhraseNode createPhraseNode(ContentNode parent, String context, List<String> text, Map<String, Object> attributes, Map<Object, Object> options) {

    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    options.put(Options.ATTRIBUTES, attributes);

    RubyHash convertMapToRubyHashWithSymbols = RubyHashUtil.convertMapToRubyHashWithSymbolsIfNecessary(rubyRuntime,
            options);

    RubyArray rubyText = rubyRuntime.newArray();
    rubyText.addAll(text);

    IRubyObject[] parameters = {
            ((ContentNodeImpl) parent).getRubyObject(),
            RubyUtils.toSymbol(rubyRuntime, context),
            rubyText,
            convertMapToRubyHashWithSymbols};
    return (PhraseNode) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.INLINE_CLASS, parameters);
}
 
Example #8
Source File: RubyDataBag.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * This is an implementation of the each method which opens up the Enumerable interface,
 * and makes it very convenient to iterate over the elements of a DataBag. Note that currently,
 * due to a deficiency in JRuby, it is not possible to call each without a block given.
 *
 * @param context the context the method is being executed in
 * @param block   a block to call on the elements of the bag
 * @return        enumerator object if null block given, nil otherwise
 */
@JRubyMethod
public IRubyObject each(ThreadContext context, Block block) throws ExecException{
    Ruby runtime = context.getRuntime();

    if (!block.isGiven())
        return PigJrubyLibrary.enumeratorize(runtime, this, "each");
    /*  In a future release of JRuby when enumeratorize is made public (which is planned), should replace the above with the below
    if (!block.isGiven())
        return RubyEnumerator.enumeratorize(context.getRuntime(), this, "each");
    */

    for (Tuple t : this)
        block.yield(context, PigJrubyLibrary.pigToRuby(runtime, t));

    return context.nil;
}
 
Example #9
Source File: TextAreaReadline.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Hooks this <code>TextAreaReadline</code> instance into the runtime,
 * redefining the <code>Readline</code> module so that it uses this object.
 * This method does not redefine the standard input-output streams. If you
 * need that, use {@link #hookIntoRuntimeWithStreams(Ruby)}.
 *
 * @param runtime The runtime.
 * @see #hookIntoRuntimeWithStreams(Ruby)
 */
public void hookIntoRuntime(final Ruby runtime) {
    this.runtime = runtime;
    /* Hack in to replace usual readline with this */
    runtime.getLoadService().require("readline");
    RubyModule readlineM = runtime.fastGetModule("Readline");

    readlineM.defineModuleFunction("readline", new Callback() {
        public IRubyObject execute(IRubyObject recv, IRubyObject[] args,
                                   Block block) {
            String line = readLine(args[0].toString());
            if (line != null) {
                return RubyString.newUnicodeString(runtime, line);
            } else {
                return runtime.getNil();
            }
        }

        public Arity getArity() {
            return Arity.twoArguments();
        }
    });
}
 
Example #10
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * setWriter - based on ScriptContainer#setWriter
 * 
 * @param ostream
 */
protected IRubyObject setWriter(OutputStream ostream)
{
	Ruby runtime = this.getRuntime();
	IRubyObject oldValue = runtime.getObject().getConstant(STDOUT_CONSTANT);

	if (ostream != null)
	{
		PrintStream pstream = new PrintStream(ostream);
		RubyIO io = new RubyIO(runtime, pstream);

		io.getOpenFile().getMainStream().setSync(true);
		setWriter(io);
	}

	return oldValue;
}
 
Example #11
Source File: IncludeProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final IncludeProcessor includeProcessor) {
    RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), "IncludeProcessor", new JRubyAsciidoctorObjectAllocator(asciidoctor) {
        @Override
        public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
            return new IncludeProcessorProxy(asciidoctor, klazz, includeProcessor);
        }
    });

    applyAnnotations(includeProcessor.getClass(), rubyClass);

    ProcessorProxyUtil.defineAnnotatedMethods(rubyClass, IncludeProcessorProxy.class);
    return rubyClass;
}
 
Example #12
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Ruby getRuntime()
{
	lazyLoad();
	if (real == null)
	{
		return null;
	}
	return real.getRuntime();
}
 
Example #13
Source File: JRubyRackApplicationTest.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
@Test public void callParsesTheResponseStatusFromAString() {
  IRubyObject callable = Ruby.getGlobalRuntime()
      .evalScriptlet("proc { |env| ['201', {'Content-Type' => 'text/plain'}, env.keys] }");
  app = new JRubyRackApplication(callable);

  RackResponse response = app.call(env);
  assertThat(response.getStatus()).isEqualTo(201);
}
 
Example #14
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is a ruby method which takes an array of arguments and constructs a Bag schema from them. The name
 * will be set automatically.
 *
 * @param context the context the method is being executed in
 * @param self    the RubyClass for the Class object this was invoked on
 * @param arg     a list of arguments to instantiate the new RubySchema
 * @return        the new RubySchema
 */
@JRubyMethod(meta = true, name = {"b", "bag"})
public static RubySchema bag(ThreadContext context, IRubyObject self, IRubyObject arg) {
    Schema s = tuple(context, self, arg).getInternalSchema();
    Ruby runtime = context.getRuntime();
    try {
        return new RubySchema(runtime, runtime.getClass("Schema"), new Schema(new Schema.FieldSchema("bag_0", s, DataType.BAG)));
    } catch (FrontendException e) {
        throw new RuntimeException("Error making map", e);
    }
}
 
Example #15
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handleContextsAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(Contexts.class)) {
        Contexts contexts = processor.getAnnotation(Contexts.class);
        RubyArray contextList = rubyRuntime.newArray();
        for (String value : contexts.value()) {
            contextList.add(rubyRuntime.newSymbol(value.substring(1)));
        }
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("contexts"),
                contextList
        });

    }
}
 
Example #16
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Row createTableRow(Table parent) {
    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    RubyArray rubyRow = rubyRuntime.newArray();
    return new RowImpl(rubyRow);
}
 
Example #17
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handleContentModelAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(ContentModel.class)) {
        ContentModel contentModel = processor.getAnnotation(ContentModel.class);
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("content_model"),
                rubyRuntime.newSymbol(contentModel.value().substring(1))
        });
    }
}
 
Example #18
Source File: SyntaxHighlighterProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static <T extends SyntaxHighlighterAdapter> RubyClass register(JRubyAsciidoctor asciidoctor, final Class<T> highlighterClass) {
  Ruby rubyRuntime = asciidoctor.getRubyRuntime();
  RubyModule module = rubyRuntime.defineModule(getModuleName(highlighterClass));

  RubyClass syntaxHighlighterBase = rubyRuntime.getModule("Asciidoctor")
      .getModule("SyntaxHighlighter")
      .getClass("Base");

  RubyClass clazz = module.defineClassUnder(
      highlighterClass.getSimpleName(),
      syntaxHighlighterBase,
      new SyntaxHighlighterProxy.Allocator(highlighterClass, asciidoctor));

  clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "initialize");
  clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "hasDocInfo");
  clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "getDocInfo");

  if (StylesheetWriter.class.isAssignableFrom(highlighterClass)) {
    clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "isWriteStylesheet");
    clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "writeStylesheet");
  }

  if (Highlighter.class.isAssignableFrom(highlighterClass)) {
    clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "isHighlight");
    clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "highlight");
  }

  if (Formatter.class.isAssignableFrom(highlighterClass)) {
    clazz.defineAnnotatedMethod(SyntaxHighlighterProxy.class, "format");
  }

  return clazz;
}
 
Example #19
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is a ruby method which takes an array of arguments and constructs a Map schema from them. The name
 * will be set automatically.
 *
 * @param context the context the method is being executed in
 * @param self    the RubyClass for the Class object this was invoked on
 * @param arg     a list of arguments to instantiate the new RubySchema
 * @return        the new RubySchema
 */
@JRubyMethod(meta = true, name = {"m", "map"})
public static RubySchema map(ThreadContext context, IRubyObject self, IRubyObject arg) {
    Schema s = tuple(context, self, arg).getInternalSchema();
    Ruby runtime = context.getRuntime();
    try {
        return new RubySchema(runtime, runtime.getClass("Schema"), new Schema(new Schema.FieldSchema("map_0", s.getField(0).schema, DataType.MAP)));
    } catch (FrontendException e) {
        throw new RuntimeException("Error making map", e);
    }
}
 
Example #20
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This allows the users to set an index or a range of values to
 * a specified RubySchema. The first argument must be a Fixnum or Range,
 * and the second argument may optionally be a Fixnum. The given index
 * (or range of indices) will be replaced by a RubySchema instantiated
 * based on the remaining arguments.
 *
 * @param context the contextthe method is being executed in
 * @param args    a varargs which has to be at least length two.
 * @return        the RubySchema that was added
 */
@JRubyMethod(name = {"[]=", "set"}, required = 2, rest = true)
public RubySchema set(ThreadContext context, IRubyObject[] args) {
    IRubyObject arg1 = args[0];
    IRubyObject arg2 = args[1];
    IRubyObject[] arg3 = Arrays.copyOfRange(args, 1, args.length);
    Schema s = internalSchema;
    Ruby runtime = context.getRuntime();
    List<Schema.FieldSchema> lfs = s.getFields();
    int min, max;
    if (arg1 instanceof RubyFixnum && arg2 instanceof RubyFixnum) {
        min = (int)((RubyFixnum)arg1).getLongValue();
        max = (int)((RubyFixnum)arg2).getLongValue();
        arg3 = Arrays.copyOfRange(args, 2, args.length);
    } else if (arg1 instanceof RubyFixnum) {
        min = (int)((RubyFixnum)arg1).getLongValue();
        max = min + 1;
    } else if (arg1 instanceof RubyRange) {
        min = (int)((RubyFixnum)((RubyRange)arg1).min(context, Block.NULL_BLOCK)).getLongValue();
        max = (int)((RubyFixnum)((RubyRange)arg1).max(context, Block.NULL_BLOCK)).getLongValue() + 1;
    } else {
        throw new RuntimeException("Bad arguments given to get function: ( " + arg1.toString() + " , " + arg2.toString()+ " )");
    }
    for (int i = min; i < max; i++)
        lfs.remove(min);
    if (arg3 == null || arg3.length == 0)
        throw new RuntimeException("Must have schema argument for []=");
    RubySchema rs = new RubySchema(runtime, runtime.getClass("Schema")).initialize(arg3);
    for (Schema.FieldSchema fs : rs.getInternalSchema().getFields())
        lfs.add(min++, fs);
    RubySchema.fixSchemaNames(internalSchema);
    return rs;
}
 
Example #21
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handleLocationAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(Location.class)) {
        Location location = processor.getAnnotation(Location.class);
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("location"),
                rubyRuntime.newSymbol(location.value().optionValue().substring(1))
        });
    }
}
 
Example #22
Source File: PreprocessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final Preprocessor preprocessor) {
    RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), "Preprocessor", new JRubyAsciidoctorObjectAllocator(asciidoctor) {
        @Override
        public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
            return new PreprocessorProxy(asciidoctor, klazz, preprocessor);
        }
    });

    applyAnnotations(preprocessor.getClass(), rubyClass);

    ProcessorProxyUtil.defineAnnotatedMethods(rubyClass, PreprocessorProxy.class);
    return rubyClass;
}
 
Example #23
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * unapplyStreams
 */
protected void unapplyStreams()
{
	Ruby runtime = this.getRuntime();

	// turn off verbose mode (and warnings)
	boolean isVerbose = runtime.isVerbose();
	runtime.setVerbose(runtime.getNil());

	// restore original values for STDIN/OUT/ERR
	this.setReader(this._oldReader);
	this.setWriter(this._oldWriter);
	this.setErrorWriter(this._oldErrorWriter);

	// remove CONSOLE/$console
	if (this._oldConsole == null)
	{
		runtime.getObject().remove_const(runtime.getCurrentContext(), runtime.newString(CONSOLE_CONSTANT));
	}
	else
	{
		this.setConsole(this._oldConsole);
	}

	// restore verbose mode
	runtime.setVerbose((isVerbose) ? runtime.getTrue() : runtime.getFalse());
}
 
Example #24
Source File: TreeprocessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final Treeprocessor treeProcessor) {
    RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), "Treeprocessor", new JRubyAsciidoctorObjectAllocator(asciidoctor) {
        @Override
        public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
            return new TreeprocessorProxy(this.asciidoctor, klazz, treeProcessor);
        }
    });

    applyAnnotations(treeProcessor.getClass(), rubyClass);

    rubyClass.defineAnnotatedMethods(TreeprocessorProxy.class);
    return rubyClass;
}
 
Example #25
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * setWriter
 * 
 * @param io
 */
protected void setWriter(IRubyObject io)
{
	Ruby runtime = this.getRuntime();

	runtime.defineVariable(new OutputGlobalVariable(runtime, STDOUT_GLOBAL, io));
	runtime.defineGlobalConstant(STDOUT_CONSTANT, io);
	runtime.getGlobalVariables().alias(STDOUT_GLOBAL2, STDOUT_GLOBAL);
	runtime.getGlobalVariables().alias(DEFOUT_GLOBAL, STDOUT_GLOBAL);
}
 
Example #26
Source File: InlineMacroProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final InlineMacroProcessor inlineMacroProcessor) {
    RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), SUPER_CLASS_NAME, new JRubyAsciidoctorObjectAllocator(asciidoctor) {
        @Override
        public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
            return new InlineMacroProcessorProxy(asciidoctor, klazz, inlineMacroProcessor);
        }
    });

    applyAnnotations(inlineMacroProcessor.getClass(), rubyClass);

    ProcessorProxyUtil.defineAnnotatedMethods(rubyClass, InlineMacroProcessorProxy.class);
    return rubyClass;
}
 
Example #27
Source File: WhenAnAsciidoctorClassIsInstantiatedInAnEnvironmentWithGemPath.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Test
public void should_have_gempath_in_ruby_env_when_created_with_default_create() {
    // Given: Our environment is polluted (Cannot set these env vars here, so just check that gradle has set them correctly)
    assertThat(System.getenv("GEM_PATH"), notNullValue());
    assertThat(System.getenv("GEM_HOME"), notNullValue());

    // When: A new Asciidoctor instance is created passing in no GEM_PATH
    Asciidoctor asciidoctor = AsciidoctorJRuby.Factory.create();

    // Then: The org.jruby.JRuby instance sees this variable
    Ruby rubyRuntime = JRubyRuntimeContext.get(asciidoctor);
    assertThat(rubyRuntime.evalScriptlet("ENV['GEM_PATH']"), is(rubyRuntime.getNil()));
    assertThat(rubyRuntime.evalScriptlet("ENV['GEM_HOME']"), is(rubyRuntime.getNil()));
}
 
Example #28
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * applyEnvironment
 * 
 * @param container
 */
protected void applyEnvironment()
{
	Ruby runtime = this.getRuntime();
	IRubyObject env = runtime.getObject().getConstant(ENV_PROPERTY);

	if (env != null && env instanceof RubyHash)
	{
		RubyHash hash = (RubyHash) env;

		// save copy for later
		this._originalEnvironment = (RubyHash) hash.dup();

		hash.putAll(this.getContributedEnvironment());

		// Grab all the matching env objects contributed via bundles that have scope matching!
		IModelFilter filter = new ScopeFilter((String) hash.get("TM_CURRENT_SCOPE")); //$NON-NLS-1$
		List<EnvironmentElement> envs = BundleManager.getInstance().getEnvs(filter);
		ScopeSelector.sort(envs);
		for (EnvironmentElement e : envs)
		{
			RubyProc invoke = e.getInvokeBlock();
			if (invoke != null)
			{
				invoke.call(runtime.getCurrentContext(), new IRubyObject[] { hash });
			}
		}
	}
}
 
Example #29
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handleNameAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(Name.class)) {
        Name name = processor.getAnnotation(Name.class);
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("name"),
                rubyRuntime.newString(name.value())
        });
    }
}
 
Example #30
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Column createTableColumn(Table parent, int index, Map<String, Object> attributes) {
    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    RubyHash rubyAttributes = RubyHash.newHash(rubyRuntime);
    rubyAttributes.putAll(attributes);

    IRubyObject[] parameters = {
            ((StructuralNodeImpl) parent).getRubyObject(),
            RubyFixnum.newFixnum(rubyRuntime, index),
            rubyAttributes}; // No cursor parameter yet

    return (Column) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.TABLE_COLUMN_CLASS, parameters);
}