org.jruby.runtime.builtin.IRubyObject Java Examples

The following examples show how to use org.jruby.runtime.builtin.IRubyObject. 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
/**
 * setConsole
 * 
 * @param ostream
 */
protected IRubyObject setConsole(OutputStream ostream)
{
	Ruby runtime = getRuntime();
	RubyClass object = runtime.getObject();
	IRubyObject oldValue = null;

	// CONSOLE will only exist already if one command invokes another
	if (object.hasConstant(CONSOLE_CONSTANT))
	{
		oldValue = object.getConstant(CONSOLE_CONSTANT);
	}

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

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

	return oldValue;
}
 
Example #2
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 #3
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 #4
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * This calls to the static method compare of DataByteArray. Given two DataByteArrays, it will call it
 * on the underlying bytes.
 *
 * @param context the context the method is being executed in
 * @param self    an class which contains metadata on the calling class (required for static Ruby methods)
 * @param arg1    a RubyDataByteArray or byte array to compare
 * @param arg2    a RubyDataByteArray or byte array to compare
 * @return        the Fixnum result of comparing arg1 and arg2's bytes
 */
@JRubyMethod
public static RubyFixnum compare(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2) {
    byte[] buf1, buf2;
    if (arg1 instanceof RubyDataByteArray) {
        buf1 = ((RubyDataByteArray)arg1).getDBA().get();
    } else {
        buf1 = (byte[])arg1.toJava(byte[].class);
    }
    if (arg2 instanceof RubyDataByteArray) {
        buf2 = ((RubyDataByteArray)arg2).getDBA().get();
    } else {
        buf2 = (byte[])arg2.toJava(byte[].class);
    }
    return RubyFixnum.newFixnum(context.getRuntime(), DataByteArray.compare(buf1, buf2));
}
 
Example #5
Source File: RubyHashUtil.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
private static IRubyObject toRubyObject(Ruby rubyRuntime, Object value) {

        if (value instanceof List) {
            return toRubyArray(rubyRuntime, (List<Object>) value);
        } else if (value instanceof Map) {
        	return convertMapToRubyHashWithStrings(rubyRuntime, (Map<String, Object>) value);
        } else {

            if (isNotARubySymbol(value)) {
                CharSequence stringValue = ((CharSequence) value);

                if (stringValue.length() > 0 && stringValue.charAt(0) == ':') {
                    return RubyUtils.toSymbol(rubyRuntime, stringValue.subSequence(1, stringValue.length()).toString());
                }
            }

            IRubyObject iRubyObject = JavaEmbedUtils.javaToRuby(rubyRuntime, value);
            return iRubyObject;
        }
    }
 
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: JavaDissectorLibrary.java    From logstash-filter-dissect with Apache License 2.0 6 votes vote down vote up
@JRubyMethod(name = "initialize", required = 2, optional = 2)
public IRubyObject rubyInitialize(final ThreadContext ctx, final IRubyObject[] args) {
    final Ruby ruby = ctx.runtime;
    try {
        dissectors = DissectPair.createArrayFromHash((RubyHash) args[0]);
    } catch (final InvalidFieldException e) {
        throw new RaiseException(e, JavaDissectorLibrary.NativeExceptions.newFieldFormatError(ruby, e));
    }
    plugin = (RubyObject) args[1];
    pluginMetaClass = plugin.getMetaClass();
    conversions = ConvertPair.createArrayFromHash((RubyHash) args[2]);
    for (final ConvertPair convertPair : conversions) {
        if (convertPair.converter().isInvalid()) {
            final RubyClass klass = ruby.getModule("LogStash").getClass("ConvertDatatypeFormatError");
            final String errorMessage = String.format("Dissector datatype conversion, datatype not supported: %s", convertPair.type());
            throw new RaiseException(ruby, klass, errorMessage, true);
        }
    }
    runMatched = args[3] == null || args[3].isTrue();
    failureTags = fetchFailureTags(ctx);
    return ctx.nil;
}
 
Example #8
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 #9
Source File: BrowserContextContributor.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public void modifyContext(CommandElement command, CommandContext context)
{
	if (command != null)
	{
		Ruby runtime = command.getRuntime();
		if (runtime != null)
		{
			IRubyObject rubyInstance = ScriptUtils.instantiateClass(runtime, ScriptUtils.RUBLE_MODULE, "Browser"); //$NON-NLS-1$
			context.put("browser", rubyInstance); //$NON-NLS-1$
		}
		else
		{
			context.put("browser", null); //$NON-NLS-1$
		}
	}
}
 
Example #10
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
public IRubyObject getRubyProperty(String propertyName, Object... args) {
    ThreadContext threadContext = runtime.getThreadService().getCurrentContext();

    IRubyObject result;
    if (propertyName.startsWith("@")) {
        if (args != null && args.length > 0) {
            throw new IllegalArgumentException("No args allowed for direct field access");
        }
        result = rubyNode.getInstanceVariables().getInstanceVariable(propertyName);
    } else {
        if (args == null) {
            result = rubyNode.callMethod(threadContext, propertyName);
        } else {
            IRubyObject[] rubyArgs = new IRubyObject[args.length];
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof RubyObjectWrapper) {
                    rubyArgs[i] = ((RubyObjectWrapper) args[i]).getRubyObject();
                } else {
                    rubyArgs[i] = JavaEmbedUtils.javaToRuby(runtime, args[i]);
                }
            }
            result = rubyNode.callMethod(threadContext, propertyName, rubyArgs);
        }
    }
    return result;
}
 
Example #11
Source File: JRubyCacheBackendLibrary.java    From thread_safe with Apache License 2.0 5 votes vote down vote up
private ConcurrentHashMap<IRubyObject, IRubyObject> toCHM(ThreadContext context, IRubyObject options) {
    Ruby runtime = context.getRuntime();
    if (!options.isNil() && options.respondsTo("[]")) {
        IRubyObject rInitialCapacity = options.callMethod(context, "[]", runtime.newSymbol("initial_capacity"));
        IRubyObject rLoadFactor      = options.callMethod(context, "[]", runtime.newSymbol("load_factor"));
        int initialCapacity = !rInitialCapacity.isNil() ? RubyNumeric.num2int(rInitialCapacity.convertToInteger()) : DEFAULT_INITIAL_CAPACITY;
        float loadFactor    = !rLoadFactor.isNil() ?      (float)RubyNumeric.num2dbl(rLoadFactor.convertToFloat()) : DEFAULT_LOAD_FACTOR;
        return newCHM(initialCapacity, loadFactor);
    } else {
        return newCHM();
    }
}
 
Example #12
Source File: ConcurrentHashMapV8.java    From thread_safe with Apache License 2.0 5 votes vote down vote up
int rubyCompare(RubyObject l, RubyObject r) {
    ThreadContext context = l.getMetaClass().getRuntime().getCurrentContext();
    IRubyObject result;
    try {
        result = l.callMethod(context, "<=>", r);
    } catch (RaiseException e) {
        // handle objects "lying" about responding to <=>, ie: an Array containing non-comparable keys
        if (context.runtime.getNoMethodError().isInstance(e.getException())) {
            return 0;
        }
        throw e;
    }

    return result.isNil() ? 0 : RubyNumeric.num2int(result.convertToInteger());
}
 
Example #13
Source File: NodeConverter.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static IRubyObject asRubyObject(Object o) {
    if (o instanceof IRubyObject) {
        return (IRubyObject) o;
    } else if (o instanceof RubyObjectHolderProxy) {
        return ((RubyObjectHolderProxy) o).__ruby_object();
    } else {
        throw new IllegalArgumentException(o.getClass() + " is not a IRubyObject nor a RubyObjectHolderProxy!");
    }
}
 
Example #14
Source File: BlockMacroProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final BlockMacroProcessor blockMacroProcessor) {
    RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), "BlockMacroProcessor", new JRubyAsciidoctorObjectAllocator(asciidoctor) {
        @Override
        public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
            return new BlockMacroProcessorProxy(asciidoctor, klazz, blockMacroProcessor);
        }
    });

    applyAnnotations(blockMacroProcessor.getClass(), rubyClass);

    ProcessorProxyUtil.defineAnnotatedMethods(rubyClass, BlockMacroProcessorProxy.class);
    return rubyClass;
}
 
Example #15
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handleDefaultAttributesAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(DefaultAttributes.class)) {
        DefaultAttributes defaultAttributes = processor.getAnnotation(DefaultAttributes.class);
        RubyHash defaultAttrs = RubyHash.newHash(rubyRuntime);
        for (DefaultAttribute defaultAttribute : defaultAttributes.value()) {
            defaultAttrs.put(defaultAttribute.key(), defaultAttribute.value());
        }
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("default_attrs"),
                defaultAttrs
        });
    }
}
 
Example #16
Source File: DocumentImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Title getStructuredDoctitle() {
    Ruby runtime = getRubyObject().getRuntime();
    RubyHash options = RubyHash.newHash(runtime);
    RubySymbol partitioned = RubySymbol.newSymbol(runtime, "partition");
    options.put(partitioned, RubyBoolean.newBoolean(runtime, true));

    Object doctitle = getRubyProperty("doctitle", options);

    return toJava((IRubyObject) doctitle, Title.class);

}
 
Example #17
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public int getInt(String propertyName, Object... args) {
    IRubyObject result = getRubyProperty(propertyName, args);
    if (result instanceof RubyNil) {
        return 0;
    } else {
        return (int) ((RubyNumeric) result).getLongValue();
    }
}
 
Example #18
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method provides addition semantics, modifying the original Schema in place.
 * This method can be given any number of arguments, much as with the constructor.
 *
 * @param context the context the method is being executed in
 * @param args    a varargs which can be any valid set of arguments that
 *                can initialize a RubySchema
 */
@JRubyMethod(name = "add!", rest = true)
public void addInPlace(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();
    List<Schema.FieldSchema> lfs = internalSchema.getFields();
    RubySchema rs = new RubySchema(runtime, runtime.getClass("Schema")).initialize(args);
    for (Schema.FieldSchema fs : rs.getInternalSchema().getFields())
        lfs.add(fs);
    RubySchema.fixSchemaNames(internalSchema);
}
 
Example #19
Source File: ExtensionGroupImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "register_extensions", required = 2)
public IRubyObject registerExtensions(ThreadContext context, IRubyObject registry, IRubyObject rubyRegistrators) {
  List<Registrator> registrators = (List<Registrator>) JavaEmbedUtils.rubyToJava(rubyRegistrators);
  for (Registrator registrator: registrators) {
    registrator.register(registry);
  }
  return context.getRuntime().getNil();
}
 
Example #20
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * Given two RubyDataByteArrays, initializes the encapsulated DataByteArray
 * to be a concatentation of the copied bits of the first and second.
 *
 * @param arg1 the first RubyDataByteArray whose bits will be used
 * @param arg2 the second RubyDataByteArray whose bits will be concatenated
               after the first's
 * @return     the initialized RubyDataBytearray
 */
@JRubyMethod
public RubyDataByteArray initialize(IRubyObject arg1, IRubyObject arg2) {
    if (arg1 instanceof RubyDataByteArray && arg2 instanceof RubyDataByteArray) {
       internalDBA = new DataByteArray(((RubyDataByteArray)arg1).getDBA(), ((RubyDataByteArray)arg2).getDBA());
    } else {
        throw new IllegalArgumentException("Invalid arguments passed to DataByteArray");
    }
    return this;
}
 
Example #21
Source File: BlockProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "process", required = 3)
public IRubyObject process(ThreadContext context, IRubyObject parent, IRubyObject reader, IRubyObject attributes) {
    Object o = getProcessor().process(
            (StructuralNode) NodeConverter.createASTNode(parent),
            new ReaderImpl(reader),
            new RubyAttributesMapDecorator((RubyHash) attributes));

    return convertProcessorResult(o);
}
 
Example #22
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public String getSymbol(String propertyName, Object... args) {
    IRubyObject result = getRubyProperty(propertyName, args);

    if (result instanceof RubyNil) {
        return null;
    }
    return result.asJavaString();
}
 
Example #23
Source File: RubyRipper.java    From gocd with Apache License 2.0 5 votes vote down vote up
@JRubyMethod
public IRubyObject column(ThreadContext context) {
    if (!parser.hasStarted()) throw context.runtime.newArgumentError("method called for uninitialized object");

    if (!parseStarted) return context.nil;

    return context.runtime.newFixnum(parser.getColumn());
}
 
Example #24
Source File: ExtensionGroupImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public ExtensionGroup rubyPreprocessor(final String preprocessor) {
  registrators.add(new Registrator() {
    @Override
    public void register(IRubyObject registry) {
      registry.callMethod(rubyRuntime.getCurrentContext(), "preprocessor", new IRubyObject[]{rubyRuntime.newString(preprocessor)});
    }
  });
  return this;
}
 
Example #25
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 #26
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * setReader
 * 
 * @param io
 */
protected void setReader(IRubyObject io)
{
	Ruby runtime = this.getRuntime();

	runtime.defineVariable(new InputGlobalVariable(runtime, STDIN_GLOBAL, io));
	runtime.defineGlobalConstant(STDIN_CONSTANT, io);
}
 
Example #27
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Block createBlock(StructuralNode parent, String context,
                         Map<Object, Object> options) {

    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    RubyHash convertMapToRubyHashWithSymbols = RubyHashUtil.convertMapToRubyHashWithSymbolsIfNecessary(rubyRuntime,
            filterBlockOptions(parent, options, "subs", ContentModel.KEY));

    IRubyObject[] parameters = {
            ((StructuralNodeImpl) parent).getRubyObject(),
            RubyUtils.toSymbol(rubyRuntime, context),
            convertMapToRubyHashWithSymbols};
    return (Block) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.BLOCK_CLASS, parameters);
}
 
Example #28
Source File: ExtensionGroupImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public ExtensionGroup rubyInlineMacro(final String macroName, final String inlineMacroProcessor) {
  registrators.add(new Registrator() {
    @Override
    public void register(IRubyObject registry) {
      registry.callMethod(rubyRuntime.getCurrentContext(), "inline_macro", new IRubyObject[]{rubyRuntime.newString(inlineMacroProcessor), rubyRuntime.newSymbol(macroName)});
    }
  });
  return this;
}
 
Example #29
Source File: RubyRipper.java    From gocd with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject src,IRubyObject file, IRubyObject line) {
    filename = filenameAsString(context, file).dup();
    parser = new RipperParser(context, this, source(context, src, filename.asJavaString(), lineAsInt(context, line)));

    return context.nil;
}
 
Example #30
Source File: ConvertPair.java    From logstash-filter-dissect with Apache License 2.0 5 votes vote down vote up
static ConvertPair[] createArrayFromHash(final RubyHash hash) {
    if (hash.isNil()) {
        return EMPTY_ARRAY;
    }
    // a hash iterator that is independent of JRuby 1.7 and 9.0 (Visitor vs VisitorWithState)
    // this does not use unchecked casts
    // RubyHash inst.to_a() creates an array of arrays each having the key and value as elements
    final IRubyObject[] convertPairs = hash.to_a().toJavaArray();
    final ConvertPair[] pairs = new ConvertPair[convertPairs.length];
    for (int idx = 0; idx < convertPairs.length; idx++) {
        pairs[idx] = create((RubyArray) convertPairs[idx]);
    }
    return pairs;
}