application wide global variable

人盡茶涼 提交于 2020-01-02 00:49:13

问题


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

For example, I would like to have a CUSTOMER_NAME='John' variable which can be accessed in helper, rake task, controller and model. Where should I define this variable in Rails app?

I am using Rails v2.3.2


回答1:


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

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




回答2:


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

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

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

MyApp::Application.config.my_key

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




回答3:


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 Hash in the #env method.



来源:https://stackoverflow.com/questions/8356378/application-wide-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!