如何在 Rails 中定义自定义配置变量 [英] How to define custom configuration variables in rails
问题描述
我想知道如何将自定义配置变量添加到 rails 应用程序以及如何在控制器中访问它们,例如,我希望能够在配置文件中定义一个 upload_directory 说 development.rb 并能够访问它在我的一个控制器中.
I was wondering how to add custom configuration variables to a rails application and how to access them in the controller, for e.g I want to be able to define an upload_directory in the configuration files say development.rb and be able to access it in one of my controllers.
其次,我计划在我的应用程序中为上传提供 S3 支持,如果我想添加一个带有 s3 访问权限的 yaml 文件、密钥、如何在我的 Rails 应用程序中初始化它以及如何访问这些值我已经在那个配置文件中定义了.
Secondly I was planning to have S3 support for uploads in my application, if I wanted to add a yaml file with the s3 access, secret key, how do I initialize it in my Rails App and how do I access the values that I have defined in that config file.
推荐答案
更新 1
非常推荐:我现在正在使用 Rails Config gem,因为它提供了细粒度的控制.
Very recommended: I'm going with Rails Config gem nowadays for the fine grained control it provides.
更新 2
如果您想要快速解决方案,请查看下面的Jack Pratt 的回答.
If you want a quick solution, then check Jack Pratt's answer below.
虽然我在下面的原始答案仍然有效,但这个答案现在已经过时了.我建议查看更新 1 和 2.
原答案:
如需快速解决方案,请观看YAML 配置文件"截屏作者 Ryan Bates 应该非常有帮助.
For a quick solution, watching the "YAML Configuration File" screen cast by Ryan Bates should be very helpful.
总结:
# config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
# application.rb
if APP_CONFIG['perform_authentication']
# Do stuff
end
这篇关于如何在 Rails 中定义自定义配置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!