Shell out from ruby while setting an environment variable
system({"MYVAR" => "42"}, "echo $MYVAR")
system
accepts any arguments that Process.spawn
accepts.
Ruby 1.9 includes Process::spawn
which allows an environ hash to be provided.
Process::spawn
is also the foundation for system
, exec
, popen
, etc.
You can pass an environment to each.
Under Ruby 1.8, you may want to consider the POSIX::Spawn
library,
which provides the same interfaces
Using your same approach, but wrapped up as a block method that temporarily modifies the environment (like the block form of Dir.chdir
):
def with_environment(variables={}) if block_given? old_values = variables.map{ |k,v| [k,ENV[k]] } begin variables.each{ |k,v| ENV[k] = v } result = yield ensure old_values.each{ |k,v| ENV[k] = v } end result else variables.each{ |k,v| ENV[k] = v } endendwith_environment 'RBENV_VERSION'=>'system' do `ruby extconf.rb`end