Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put Global variables in Rails 3

Tags:

I used to put Global variables in environment.rb with my Rails 2.3.8 application such as:

MAX_ALLOWD_ITEMS = 6 

It doesn't seem to work in Rails 3. I tried putting it in application.rb and that didn't help.

What do you suggest?

like image 957
Tam Avatar asked Aug 30 '10 08:08

Tam


People also ask

Where should I declare global variables?

We mostly declare global variables at the top of a module file. Any function we define at any point in the program can change any global variable. The function printName() can access the global variable companyName even though it is declared outside the function.

How do you use a global variable in Ruby?

Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($).

What are two different scopes variables can have in Ruby?

What is Variable Scope? Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, local, global, instance and class.

How do you define a local variable in Ruby?

Local Variables: A local variable name always starts with a lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method.


1 Answers

If you have already tried restarting your server as Ryan suggested, try putting it in your application.rb like this:

module MyAppName   class Application < Rails::Application     YOUR_GLOBAL_VAR  = "test"   end end 

Then you can call it with the namespace in your controllers, views or wherever..

MyAppName::Application::YOUR_GLOBAL_VAR 

Another alternative would be using something like settingslogic. With settingslogic, you just create a yml config file and a model (Settings.rb) that points to the config file. Then you can access these settings anywhere in your rails app with:

Settings.my_setting 
like image 193
johnmcaliley Avatar answered Nov 10 '22 01:11

johnmcaliley