Jwosty
Jwosty

Reputation: 3634

Get JRuby jar path

Similar to this question, I'd like to know how to get the current jar file's path. But unlike the other question, I want to know the jar's path, not the path of the current file inside the jar. For example, say I had a jruby jar at "/Users/MyUser/Jars/foo.jar" and inside was a compiled ruby file at "foo.jar/java/style/class/path.class". How could class.path get the path "/Users/MyUser/Jars/foo.jar"?

I also saw a way to do it in Java, but I just don't know how to translate it...

Upvotes: 3

Views: 1694

Answers (2)

peter
peter

Reputation: 42182

Figured it out without using java

def get_jar_path
    scriptpath = __FILE__[/(.*)\/.+\.jar!/]
    $1[6..-1]
end

Upvotes: 0

I have experimented with this a bit, and any attempt to call the code from JRuby returns the jruby jar itself, which kind of makes sense as the logic is indeed evaluated/executed from that jar. For instance:

require 'java'
puts self.to_java.get_class().protection_domain().code_source().location().path()

or

require 'java'

class Path
  def get_jar_path
    self.to_java.get_class().protection_domain().code_source().location().path()
  end
end

puts Path.new.get_jar_path

both return the path to jruby-complete.jar, which can be useful to some extent but apparently not what you’re looking for.

The only way I could get this to work (with rawr, but this can be easily adapted if you use warbler) is to create a Java class in src/java/org/rubyforge/rawr:

package org.rubyforge.rawr;

public class Path {
  public String getJarPath() {
    return getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
  }
}

Then call this class from the JRuby script:

require 'java'
java_import 'org.rubyforge.rawr.Path'

puts Path.new.get_jar_path

Upvotes: 2

Related Questions