I need to shell out to a process while setting an environment variable for it. I tried this one-liner:
system "RBENV_VERSION=system ruby extconf.rb"
This syntax works in shell script but not from ruby. (Update: turns out this syntax works from ruby after all, but I failed to see its effect due to my particular use-case.)
So I'm doing this:
rbenv_version = ENV['RBENV_VERSION'] ENV['RBENV_VERSION'] = 'system' begin system "ruby extconf.rb" ensure ENV['RBENV_VERSION'] = rbenv_version end
I'm forced to such a long expression because I don't want to override the environment variable permanently if it already had a value.
Anything shorter that comes to your mind?
Passing Environment Variables to Ruby To pass environment variables to Ruby, simply set that environment variable in the shell. This varies slightly between operating systems, but the concepts remain the same. To set an environment variable on the Windows command prompt, use the set command.
Setting an Environment Variable To output the value of the environment variable from the shell, we use the echo command and prepend the variable's name with a dollar ($) sign. And so long as the variable has a value it will be echoed out. If no value is set then an empty line will be displayed instead.
The easiest way to set environment variables is to use the export command. Using export, your environment variable will be set for the current shell session. As a consequence, if you open another shell or if you restart your system, your environment variable won't be accessible anymore.
You store separate environment variables in config/development. rb , config/testing. rb and config/production. rb respectively.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With