So, let's say you need to use tokens into your app to access a third party API (like Twitter, Instagram or Facebook). In Ruby gems tutorials it's very common to see the following example code to load these tokens:
CONFIG = YAML.load_file(Rails.root.join("config/facebook.yml"))[Rails.env]
APP_ID = CONFIG['app_id']
SECRET = CONFIG['secret_key']
This was extracted from the Koala's gem wiki on GitHub. Or the following one, which was extracted from the README file of the Instagram gem GitHub repo.
Instagram.configure do |config|
config.client_id = "YOUR_CLIENT_ID"
config.client_secret = "YOUR_CLIENT_SECRET"
It's a very ugly practice to hardcode things like this, IMHO.
Now, the most recommended and used practice in the wild is to have these API access tokens in a YAML file, so it can be loaded into our app, like the Koala's example code from above. The format is the one that follows:
As you may know, this file is loaded as a
Hash. So we can access each key and value.
Now, using ruby's metaprogramming magic we can load each key of the file and use it the configuration section of the gem. How? Using the
CONFIG = YAML.load_file(Rails.root.join("config", "settings.yml"))[Rails.env]
Twitter.configure do |twitter|
CONFIG['twitter'].each_key do |key|
The secret is to name each key in the YAML file section exactly as the name of the configuration key of the gem, so it wont be any
You can find more information about the
.send() method in the Ruby Documentation page.