Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 496
Jwosty Avatar asked Sep 24 '26 13:09

Jwosty


1 Answers

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
like image 76
Sébastien Le Callonnec Avatar answered Sep 27 '26 20:09

Sébastien Le Callonnec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!