Learning To Code

Join me as I take the plunge!

An Alernative to Figaro

I’ve made quite a few Rails apps that require storing keys from various proviers (Amazon, Facebok, Twitter, Stripe, etc). Thus far I’ve only either hard coded the values into my app (horribly insecure, espically since I use mainly public github repositories) or used the Figaro gem (which has caused bugs occasionally). Today, however I discovered a third way.

Step 1

Make a file called env_vars.rb that includes all your keys that you want to keep secret (below, I have put in my twitter keys and tokens) and place it in the app/config folder

1
2
3
4
ENV['TWITTER_CONSUMER_KEY'] =  'your_twitter_consumer_key'
ENV['TWITTER_CONSUMER_SECRET'] =  'your_twitter_consumer_secret'
ENV['TWITTER_OAUTH_TOKEN'] =  'your_twitter_oauth_token'
ENV['TWITTER_OAUTH_TOKEN_SECRET'] =  'your_twitter_oauth_token_secret'

Step 2

In app/config/boot.rb add the following line under require ‘rubygems’:

1
require_relative 'env_vars'

Step 3

Add the following line to the end of your .gitignore file

1
/config/env_vars.rb

Step 4

Now you can use whatever environmentl variables you stored in the env_var.rb file. Here is how I call the twitter variables in one of my app’s twitter.rb initializer.

1
2
3
4
5
6
Twitter.configure do |config|
  config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
  config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
  config.oauth_token = ENV["TWITTER_OAUTH_TOKEN"]
  config.oauth_token_secret = ENV["TWITTER_OAUTH_TOKEN_SECRET"]
end

Now, I am aware that there is an even cooler way to add these environmetal variables to your .bash_profile - but I’ll leave for another time. For now, I am satisfied that I can use environmental variables in a secure, Figaro-free way!