Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

application wide global variable

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

like image 242
Mellon Avatar asked Dec 02 '11 12:12

Mellon


People also ask

What is an example of a global variable?

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.

What are two reasons why you should not use global variables?

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.

Can global variables be used anywhere?

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.


2 Answers

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

like image 163
Paul Groves Avatar answered Sep 18 '22 11:09

Paul Groves


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.

like image 25
Marek Příhoda Avatar answered Sep 21 '22 11:09

Marek Příhoda