Gangmax Blog

自由之思想,独立之精神

How to Read Configuration File in Rails

| Comments

Please read the post and watch the podcast.

The basic idea is:

  1. Define a “yml” file which contains the configuration information under the “config/” directory;

  2. Add a “initializer” ruby file(such as “load_config.rb”) in the “config/initializers/” directory which has the code to load the yml file;

  3. In your Rails code use the loaded configuration information.

config/config.yml
1
2
3
4
5
6
7
8
9
10
development:
  perform_authentication: false

test:
  perform_authentication: false

production:
  perform_authentication: true
  username: admin
  password: secret
config/initializers/load_config.rb
1
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]
application.rb
1
2
3
4
5
6
7
def authenticate
  if APP_CONFIG['perform_authentication']
    authenticate_or_request_with_http_basic do |username, password|
      username == APP_CONFIG['username'] && password == APP_CONFIG['password']
    end
  end
end

Comments