Cannot execute RVM shell commands in ruby
Long time lurker, first time poster!
Goal
My ultimate goal is to make a Rake setup script to setup my rvm environment stuff (I need to dynamically create gemsets, install gems to those gemsets, and run ruby scripts within those gemsets).
Problem
I need to setup rvm in the shell that I'm executing rvm commands in. The basic idea is to source the rvm scripts as outlined here.
The problem arises when I try and source the rvm script when executing a shell command within ruby. Its well documented that rvm only supports bash, but ruby doesn't seem to be using bash when executing shell commands.
What I've Tried
I've tried all the methods to execute shell commands listed here to no avail. I'll use the 'exec' method below for simplicity.
It seems that although ruby thinks its using the bash shell to execute these commands ... it is not. Observe!
exec 'echo $SHELL'
=> /bin/bash
But
exec 'source ~/.rvm/scripts/rvm; type rvm | head -1;'
=> sh: source: not found
=> rvm is ~/.rvm/bin/rvm
Which tells me that ruby is really using /bin/sh not /bin/bash (that output should return rvm is a function
). I even went so far as to print the ruby env stuff, and ENV[SHELL] is '/bin/bash'
'Brute Force' Solution
I do have a workaround, but its really kludgy (this would necessitate that I 'AND' all of the commands together):
exec 'echo \'source ~/.rvm/scripts/rvm && type rvm | head -1\' | /bin/bash'
I'd like to avoid using shell script开发者_开发问答s if possible -- it seems reasonable that I can accomplish this within ruby.
As it happens, RVM actually exposes a Ruby API that's included by default. Add $HOME/.rvm/lib
to your $LOAD_PATH
; you can now use require 'rvm'
.
As far as I can tell, the main documentation for this is in the source files themselves (a summary is in rvm.rb
).
Now you can write Ruby scripts that manipulate RVM, like this:
require 'rvm'
env = RVM.current
env.gemset.create('newgemset')
And so on.
Call bash with the -c parameter:
command = 'source ~/.rvm/scripts/rvm; type rvm | head -1'
exec "bash -c #{command.inspect}"
精彩评论