Mike Thomsen
Mike Thomsen

Reputation: 37506

Loading JRuby script from the Java classpath

I have a simple maven project that looks like this:

This is what InstallerLoader.java looks like:

package com.mycompany;

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

public class InstallerLoader {
    public static void main(String[] args) {
        System.out.println("Running..");
        ScriptingContainer container = new ScriptingContainer();
        container.runScriptlet(PathType.CLASSPATH, "/installer.rb");
    }
}

And this is what installer.rb looks like:

require 'optparse'

options = { :verbose => false}
optparse = OptionParser.new do |opts|
    opts.on('-v', '--verbose', 'Verbose output') do
        options[:verbose] = true
    end
end

optparse.parse!

puts options[:verbose]

When I try to run this, it doesn't seem to load installer.rb. There is no stack trace or anything else that would indicate that the installer.rb was not loaded. What am I doing wrong here?

Upvotes: 3

Views: 516

Answers (2)

Mike Thomsen
Mike Thomsen

Reputation: 37506

This is the code that finally got it to work:

container.setArgv(args);
InputStream is = this.getClass().getResourceAsStream("/installer.rb");
container.runScriptlet(is, "installer.rb");

Upvotes: 0

matts
matts

Reputation: 6887

The classpath filename shouldn't start with a /. It should just be:

container.runScriptlet(PathType.CLASSPATH, "installer.rb");

This is a quirky undocumented aspect of Java's ClassLoader API (which is of course being used under the covers by the ScriptingContainer to load files from the classpath).

Upvotes: 2

Related Questions