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

There are currently no comments.
Your Icon:
[City], [Country]
Publicly displayed.
Your email won't be displayed.
The following tags are preserved: <pre>, <em> and <a>. All comments are moderated.

Please note, you can leave a comment that uses (limited) XHTML and Textile syntax.