Environment variables with the Figaro Gem

Environment variables are a great way in Ruby on Rails to protect private information, especially when your project is publicly hosted on git.  For example, I just added email support to my Ruby on Rails app, and in order to send an email, I have to put in my username and password.  Well of course I don’t want that to become public information in the source code by hard coding it.  One way to avoid this is to put these variables into a separate file that does not get committed to github.  I’ll show you how to use the Figaro gem to do just that.

First, add the gem to your gem file and then run ‘bundle install’.  Then in the Terminal run

rails generate figaro:install

This creates a file called “config/application.yml” in your rails app.  It also automatically adds this file to your .gitignore file so it does not get committed to github.

Screen_Shot_2013-08-04_at_8.29.25_PM

Then simply add your sensitive variables in this application.yml file like this:

Screen Shot 2013-08-04 at 9.07.39 PM

Now back in your environment files such as “development.rb” or “production.rb” you can input your sensitive variables as such:

Screen Shot 2013-08-04 at 9.08.57 PM

Now your information is safe, and your environment variables are set.  If you want to set different variables for different environments, i.e. development vs production, simply give them different names in your application.yml file, and call the appropriate one in each development.rb or production.rb

UPDATE: A reminder that if you end up changing any of the information that you store in your environment variables, such as the password to your email or something, then it will not get pushed to production automatically when you commit to git. (because that’s the whole point of environment variables).  So if you do need to update your environment variables on heroku, simply run heroku config to view your current environment variables on heroku.

To set or change them, run:
heroku config:set USERNAME=username

Refer to the heroku documentation for more details. Don’t forget to do this after changing any of these variables – I spent an hour debugging, when all I needed to do was update the environment variables on heroku 😦 Hopefully this will save you some time!