Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Installing gems inside (J)Ruby code

Tags:

java

ruby

jruby

I am using JRuby along with Cucumber and is looking for a way of running

 jruby -S gem update --system
 jruby -S gem install cucumber

from within the Java ScriptEngine. No amount of Googling have let me to a solution to this problem. Basically I want to be able to do something like this

 ScriptEngineManager manager = new ScriptEngineManager();
 ScriptEngine jRubyEngine = manager.getEngineByName("jruby");
 : // some unknown code here
 jRubeEngine.eval("call gems install/update from inside JRuby")

Is there a way of accomplishing this?

like image 678
Lars Tackmann Avatar asked Feb 12 '10 11:02

Lars Tackmann


People also ask

How do you use gems in Ruby?

If you want to use a gem from within your code, you'll have to require it first. This is usually done at the top of the file. I don't believe we've discussed require before; Ruby doesn't load everything by default, so you can use require to load extra libraries you want to use.

Where does Ruby install gems?

Once you've required ap , RubyGems automatically places its lib directory on the $LOAD_PATH . That's basically it for what's in a gem. Drop Ruby code into lib , name a Ruby file the same as your gem (for the gem “freewill” the file should be freewill. rb , see also name your gem) and it's loadable by RubyGems.

How do I install gems?

To install a gem, use gem install [gem] . Browsing installed gems is done with gem list . For more information about the gem command, see below or head to RubyGems' docs. There are other sources of libraries though.

How do I push a gem to RubyGems?

From the main menu, select Tools | Gem | Push Gem. In the Run tool window, specify your RubyGems credentials. Your gem will be published to RubyGems.org.


1 Answers

RubyGems is just a Ruby library. The gem command is only a thin wrapper around the library. Everything you can do with the command, you can do with the library.

I've never actually used the library, but I guess what you want to look at is the Gem::DepencyInstaller and the code would look something like this (completely untested, just pulled out of my you-know-what):

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine jRubyEngine = manager.getEngineByName("jruby");
String s = "
  require 'rubygems'
  require 'rubygems/dependency_installer'
  Gem::DependencyInstaller.new.install('cucumber')
";
jRubyEngine.eval(s);
like image 56
Jörg W Mittag Avatar answered Oct 23 '22 14:10

Jörg W Mittag