Ruby setting ENV variables on a mac
I would like to try an keep my dev开发者_运维问答elopment machine as close as the production server (heroku in this case).
Heroku lets you define config vars ie.
config:add key=val
This is now pretty secure as secret key values are not stored in my code.
Do you know how and where can I create such environment variables per app on my local mac machine.
I have googled this and as of yet not found a good solution. Any ideas ?
Thanks in advance.
Thanks Zabba, But I have actually found a great way for me.
I am using POW to run my local apps and reading the docs I have found out that you can set Environment Vars by adding a .powenv file in the root of my app ie.
export API_KEY='abcdef123456'
You can then use in your app like normal ie.
api_key = ENV['API_KEY']
Pretty kool stuff.
Here's a way:
Go to http://railswizard.org/ and add only "EnvYAML" to the template. Click finish and then click on the generated .rb
file. See how that code is using a file config/env.yml
to set ENV vars.
Here is how it is done, thanks to http://railswizard.org/:
In your app's directory:
Append in config/application.rb
:
require 'env_yaml'
Create a file called lib/env_yaml.rb
:
require 'yaml'
begin
env_yaml = YAML.load_file(File.dirname(__FILE__) + '/../config/env.yml')
if env_hash = env_yaml[ENV['RACK_ENV'] || ENV['RAILS_ENV'] || 'development']
env_hash.each_pair do |k,v|
ENV[k] = v.to_s
end
end
rescue StandardError => e
end
Create a file called config/env.yml
:
defaults: &defaults
ENV_YAML: true
some_key: value
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
Note that ENV is not a Hash
- it only appears so because of the use of []
. That is why in lib/env_yaml.rb
an each
loop is setting in ENV the value of each value found in the config/env.yml
- because we cannot assign a Hash
directly to ENV
.
I'm not using pow but rvm and bash. I was able to set environmental variables by following the instructions at this Peachpit blog post.
Like the other answers, I had to add commands like export TWILIO_ACCOUNT_SID="XXX"
but to my ~/.profile file.
Then, accessed the variables in my code with:
account_sid = ENV["TWILIO_ACCOUNT_SID"]
Put your environment variables in a .env
file and foreman
will pick them up automatically.
精彩评论