如何在运行时访问 Rails 配置值? [英] How do I access a Rails configuration value during runtime?

查看:39
本文介绍了如何在运行时访问 Rails 配置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Rails 2.3.x.当且仅当 config.cache_classes 为真时,我想要一小段代码运行.默认情况下,对于生产来说是 true,对于开发来说是 false.

I'm using Rails 2.3.x. I would like a small section of code to run if and only if the config.cache_classes is true. By default, that's true for production and false for development.

如何从我的 environment.rb、development.rb 和 production.rb 文件之外访问 config.cache_classes 的值?很容易判断我们是在生产中还是在开发中,Rails.env 会给我们答案.但不能保证开发者没有在开发中设置 config.cache_classes = true.

How do I access the value of config.cache_classes from outside of my environment.rb, development.rb, and production.rb files? It's easy to tell if we are in production or development, Rails.env will give us the answer. But there's no guarantee the developer hasn't set config.cache_classes = true in development.

我当然理解您通常不希望在开发和生产中运行单独的代码路径.在这个特定的例子中,我们只是没有在启动时执行一些工作;如果我们需要稍后执行,我们将在开发和生产中执行.

I certainly understand that you do not generally want to run separate code paths in development and production. In this particular instance, we are simply not performing some work on startup; if we need to perform it later, we will do so, both in development and production.

推荐答案

对于 Rails 2,你可以这样做:

For Rails 2, you can do:

Rails.configuration.cache_classes

如果您切换到 Rails 3,情况会有所不同;您可以通过以下方式访问相同的值:

If you ever switch to Rails 3, it'll be different; you can access the same value with:

Rails.application.config.cache_classes

这篇关于如何在运行时访问 Rails 配置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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