Where to put Global variables in Rails 3
Solution 1:
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
Solution 2:
I usually go with application_helper.rb This is what it looks like:
module ApplicationHelper
def my_global_variable
my_global_variable = "Helloworld!"
end
end
Then I can put in my_global_variable anywhere as a function.
Solution 3:
If you are truly defining it in config/environment.rb like you say, the only way I can duplicate your problem is by running up a server using rails server
, then putting in the variable to config/environment.rb, referencing it in a view or controller somewhere and then trying to load that specific part of my application.
If I stop the server and start it again and again try to access that view or controller then it works. I reckon you just haven't restarted your server.
Solution 4:
I normally create inside config/initializers/ a yaml (yml) file with all the global site settings. remember to restart the server each time you change anything.