8ruh8a
Last Updated: February 25, 2016
·
4.062K
· kennethjohnbalgos

Custom config for Rails app

All config variables should be stored in a single file located at config\config.yml. Below is the instruction to implement that.

Implement - Create an initializer:

# config/initializers/load_config.rb
CONFIG_PATH="#{Rails.root}/config/config.yml"
APP_CONFIG = YAML.load_file(CONFIG_PATH)[Rails.env]

Configure - Create the config yaml file with 3 env:

# config/config.yml
production:
    api_url: http://sample_url/api
    api_key: d91nrRr6qM
    secret_key: oTi3k4qW82

development:
    api_url: http://localhost:3000/api
    api_key: 0e7idRmq4h
    secret_key: y8mDky3Ew1

test:
    api_url: http://localhost:3000/api
    api_key: 0e7idRmq4h
    secret_key: y8mDky3Ew1

Usage - Calling the variables:

def api_connect_url
    url = APP_CONFIG['api_url']
    api = APP_CONFIG['api_key']
    secret = APP_CONFIG['api_secret']
    return "#{url}?apikey=#{api}&secret=#{secret}"
end

Sample results:

For security reasons, I suggest to include config/config.yml in .gitignore file when using Git.