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

编程入门 行业动态 更新时间:2024-10-22 13:34:03
为我的Rails应用程序创建自定义配置选项的最佳方式?(Best way to create custom config options for my Rails app?)

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

environment.rb AUDIOCAST_URI_FORMAT = http://blablalba/blabbitybla/yadda

工作很棒

但是,我有点不安。 这是一个好办法吗? 有没有办法更臀部?

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

Works great.

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文件。 例如,它可能如下所示:

defaults: &defaults audiocast_uri_format: http://blablalba/blabbitybla/yadda development: <<: *defaults test: <<: *defaults production: <<: *defaults

该配置文件从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,请确保不会在您的相对配置路径中不小心添加主要斜杠。

然后可以使用以下命令检索该值:

uri_format = APP_CONFIG['audiocast_uri_format']

有关详细信息,请参阅Railscast 。

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

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]

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']

See this Railscast for full details.

更多推荐

environment,rb,Rails,电脑培训,计算机培训,IT培训"/> <meta name="descript

本文发布于:2023-08-02 04:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1368402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   应用程序   选项   方式   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!