如何在rails中定义自定义配置变量 [英] How to define custom configuration variables in rails

查看:99
本文介绍了如何在rails中定义自定义配置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何添加自定义配置变量到rails应用程序以及如何在控制器中访问它们,例如我想能够在配置文件中定义一个upload_directory,如development.rb,并且能够访问它我的控制器之一。



其次,我计划在我的应用程序中支持S3上传,如果我想添加一个yaml文件与s3访问,密钥,如何在我的Rails应用程序中初始化它,以及如何访问我在该配置文件中定义的值。

解决方案

更新1



非常推荐:我会使用

Update2

$

b
$ b

如果您想要快速解决方案,请查看下面的 Jack Pratt的回答。 p>

虽然下面的原始答案仍然有效,但这个答案现在已经过时了。建议您查看更新1和2。




要获得快速解决方案,请观看YAML配置文件屏幕投射

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

#应用程序。 rb
if APP_CONFIG ['perform_authentication']
#Do stuff
end


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 wanna 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.

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.

解决方案

Update 1

Very recommended: I'm going with Rails Config gem nowadays for the fine grained control it provides.

Update2

If you want a quick solution, then check Jack Pratt's answer below.

Although my original answer below still works, this answer is now outdated. I recommend looking at updates 1 and 2.

Original Answer:

For a quick solution, watching the "YAML Configuration File" screen cast by Ryan Bates should be very helpful.

In summary:

# 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆