Rails gem for read environment variables configuration, just follow some convention.
gem install loadcfg
or then add gem ‘loadcfg’ to your Gemfile and run:
bundle install
Let’s say you have some configuration variables that depend of the environment you are working on, for example config/facebook.yml
development: app_id: <the_app_id_for_development_env> secret_key: <the_secret_key_for_development_env> callback_url: <the_callback_url_for_development_env> test: app_id: <the_app_id_for_test_env> secret_key: <the_secret_key_for_test_env> callback_url: <the_callback_url_for_test_env> staging: app_id: <the_app_id_for_staging_env> secret_key: <the_secret_key_for_staging_env> callback_url: <the_callback_url_for_staging_env> production: app_id: <the_app_id_for_production_env> secret_key: <the_secret_key_for_production_env> callback_url: <the_callback_url_for_production_env>
One of the conventions is that you should put the file in the config directory of your rails project, then, in any class where you want to use the constants you just need to call loadconfig method passing the config file name as a symbol, for example:
class FacebookHelper loadconfig :facebook end
that’s going to generate a constant for each key in the yaml config file, each constant will has file name as a prefix, for example:
class FacebookHelper loadconfig :facebook def some_method_that_deals_with_facebook_api fb_id = FACEBOOK_APP_ID fb_secret_key = FACEBOOK_SECRET_KEY # here fb_id and fb_secret_key contain the values you gave them for the environment you are working on end end
There is a couple of options you can pass to loadconfig method
loadconfig :facebook, :environment => :my_environment, :ignore_not_found => true
If there’s no my_environment entry in the config/facebook.yml file there will be no exception raised.
That’s it.