我们的程序中可能有一些参数配置,我们可以将这些配置放在外部YAML文件里而不必污染应用程序代码:
[code]
# config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]
# application.rb
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
# config/config.yml
development:
perform_authentication: false
test:
perform_authentication: false
production:
perform_authentication: true
username: admin
password: secret
[/code]
[code]
# config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]
# application.rb
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
# config/config.yml
development:
perform_authentication: false
test:
perform_authentication: false
production:
perform_authentication: true
username: admin
password: secret
[/code]
本文介绍了一种使用YAML文件来管理应用程序配置的方法,通过这种方式可以有效地分离配置与代码,提高应用的灵活性。文章展示了如何在Ruby on Rails项目中加载和使用YAML配置文件。
1451

被折叠的 条评论
为什么被折叠?



