Ruby-on-rails 如何在运行时访问 Rails 配置值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4319802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:45:22  来源:igfitidea点击:

How do I access a Rails configuration value during runtime?

ruby-on-rails

提问by ChrisInEdmonton

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

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

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.envwill give us the answer. But there's no guarantee the developer hasn't set config.cache_classes = truein development.

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

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.

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

回答by molf

For Rails 2, you can do:

对于 Rails 2,您可以执行以下操作:

Rails.configuration.cache_classes

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

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

Rails.application.config.cache_classes

回答by kross

Depending on where you are in a module, you may need to access the root namespace. This should provide access from anywhere in a universal way for rails 3+:

根据您在模块中的位置,您可能需要访问根命名空间。这应该为 Rails 3+ 提供从任何地方以通用方式访问:

::Rails.application.config

::Rails.application.config