Ruby-on-rails 应用范围的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8356378/
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-03 02:25:31  来源:igfitidea点击:

application wide global variable

ruby-on-railsruby-on-rails-2

提问by Mellon

In Rails, where should I define the variable which can be recognized by every layer of Rails stacks.

Rails 中,我应该在哪里定义可以被每一层 Rails 堆栈识别的变量。

For example, I would like to have a CUSTOMER_NAME='John'variable which can be accessed in helper, raketask, controllerand model. Where should I define this variable in Railsapp?

例如,我想要一个CUSTOMER_NAME='John'可以在helperraketask、controllermodel 中访问的变量。我应该在Rails应用程序中的哪里定义这个变量?

I am using Rails v2.3.2

我正在使用Rails v2.3.2

回答by Paul Groves

In an initializer in /app/config/initializersall .rb files in here get loaded, I usually create one called preferences.rb for things like this.

/app/config/initializers所有 .rb 文件的初始值设定项中,我通常会为这样的事情创建一个名为preferences.rb 的文件。

See: http://guides.rubyonrails.org/configuring.html#using-initializer-files

请参阅:http: //guides.rubyonrails.org/configuring.html#using-initializer-files

回答by Marek P?íhoda

An alternative approach is to set a key on the config object in config/application.rb, like so:

另一种方法是在 中的配置对象上设置一个键config/application.rb,如下所示:

MyApp::Application.configure do
   # ...
   config.my_key = 'some "global" value'
end

You can then access my_keyfrom anywhere in your app with just this:

然后,您可以通过以下方式my_key从应用程序的任何位置访问:

MyApp::Application.config.my_key

Also, Mike Perham has described a similar, though a more comprehensive approach in his blog post.

此外,Mike Perham在他的博客文章中描述了一种类似但更全面的方法。

回答by Reactormonk

You want a true global constant? Use ::COSTUMER_NAME. You want a true global variable? Use $COSTUMER_NAME(discouraged). You want a request-global variable? Use the Hashin the #envmethod.

你想要一个真正的全局常量吗?使用::COSTUMER_NAME. 你想要一个真正的全局变量吗?使用$COSTUMER_NAME(不鼓励)。你想要一个请求全局变量吗?使用Hash#env方法。