Managing Ruby Environment Variables

Author: Samuel Williams When: Tuesday, 21 April 2009

I was writing a Rakefile that required to modify the ENV (environment) for scripts being executed using system(). Because I couldn't figure out how to pass environment variables directly to the child process, I've made a simple function which can (in a non-thread-safe manor) assist with this minor problem:

def environment (new_env = nil, &block)
  old_env = ENV.to_hash
 
  ENV.update(new_env) if new_env
 
  yield
 
  ENV.clear
  ENV.update(old_env)
end

It is typically used as follows:

build_env = {"CC" => "/usr/bin/gcc"}
 
environment(build_env) do
  system("make")
end

Comments

Leave a comment

Please note, comments must be formatted using Markdown. Links can be enclosed in angle brackets, e.g. <www.codeotaku.com>.