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
Example of Global Variable in C You can notice that in line 4, x and y get declared as two of the global variables of the type int. Here, the variable x will get initialized automatically to 0. Then one can use variables like x and y inside any of the given functions.
Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With