简体   繁体   中英

Set local ENV variable in Windows command from Ruby

I've made a Rake task for local dev that will build the project, start watching it for auto-compilation, and also start up a Thin server to see the compiled app.

I implemented Foreman to allow for setting up local ENV variables, which the project is now depending on. It works great - except it needs to also work on Windows.

My solution was to parse the .env files and manually set the vars in I start the server, ala:

$ MY_ENV_VAR=12345 ruby -rubygems app.rb

It works great when I execute it myself by hand. But if I try to execute that command via my Rake task - sh %{MY_ENV_VAR=12345 ruby -rubygems app.rb} , it fails:

Command failed with status (127): [MY_ENV_VAR=12345 ruby -rubygems app.rb...]

I've tried executing it with sh %{} , exec , system , %x{} , and backticks with no luck. Any suggestions?

Try using Kernel#system with the env argument :

env = {'FOO' => '123'}
cmd = 'echo $FOO'
system(env, cmd) # => prints "123", returns true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM