Lee
Lee

Reputation: 20924

Ruby setting ENV variables on a mac

I would like to try an keep my development 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.

Upvotes: 6

Views: 6252

Answers (4)

BenU
BenU

Reputation: 2317

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"]

Upvotes: 1

Dave Sag
Dave Sag

Reputation: 13486

Put your environment variables in a .env file and foreman will pick them up automatically.

Upvotes: 0

Lee
Lee

Reputation: 20924

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.

Upvotes: 8

Zabba
Zabba

Reputation: 65467

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.

Upvotes: 3

Related Questions