最好的方式为我的Rails应用程序创建自定义配置选项? [英] Best way to create custom config options for my Rails app?

查看:111
本文介绍了最好的方式为我的Rails应用程序创建自定义配置选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我的Rails应用程序创建一个配置选项。它对于所有环境可以是相同的。我发现如果我在 environment.rb 中设置它,它在我的视图中可用,这是我想要的...

I need to create one config option for my Rails application. It can be the same for all environments. I found that if I set it in environment.rb, it's available in my views, which is exactly what I want...

environment.rb

AUDIOCAST_URI_FORMAT = http://blablalba/blabbitybla/yadda

效果很好。

但是,我有点不安。这是一个很好的方法吗?是否有更髋关节的方法?

However, I'm a little uneasy. Is this a good way to do it? Is there a way that's more hip?

推荐答案

对于不需要存储在数据库表中的一般应用程序配置,我喜欢在 config 目录中创建一个 config.yml 文件。对于您的示例,它可能如下所示:

For general application configuration that doesn't need to be stored in a database table, I like to create a config.yml file within the config directory. For your example, it might look like this:

defaults: &defaults
  audiocast_uri_format: http://blablalba/blabbitybla/yadda

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

config / initializers 中的自定义初始化程序加载:

This configuration file gets loaded from a custom initializer in config/initializers:

# Rails 2
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]

# Rails 3+
APP_CONFIG = YAML.load_file(Rails.root.join('config/config.yml'))[Rails.env]

如果您使用Rails 3,

If you're using Rails 3, ensure you don't accidentally add a leading slash to your relative config path.

然后,您可以使用以下方式检索该值:

You can then retrieve the value using:

uri_format = APP_CONFIG['audiocast_uri_format']

此Railscast 了解详情。

这篇关于最好的方式为我的Rails应用程序创建自定义配置选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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