Rails Constant and Global Variables
Jul 24
I was recently faced with a common problem that I wanted to share. During development there are times you need to specifiy a global or constant variable that will be shared throughout the entire application. In ColdFusion you would normally place something like this in Application.cfm. In Rails I was uncertain how exactly to approach this. At first I thought an application.rb file made sense, but the more I thought about it I decided to take advantage of the config files.
Since my global variable was one that would be consistent regardless of environment (dev, test, and prod) I decided to place it in config/environment.rb. I placed this under the RAILS_GEM_VERSION constant:
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = ’1.1.2′
BASE_URL = ‘http://mydomain.com/’
Now referencing this in any view can be done similar to any other variable:
<%= BASE_URL %>
If you need to specify globals that are specific to environment then I recommend placing them in their appropriate config file:
/config/environments/development.rb
/config/environments/test.rb
/config/environments/production.rb

So, another former CF programmer! Okay, maybe I’m not a former one yet…it still has to pay the bills.
Anyway, thanks for the tip. These are the same kind of issue’s I’m experiencing in my switch.
No problem. I too have not abandoned CF completely because there are still things that it does VERY well. It’s great to have knowledge of both to compare and contrast different frameworks. Welcome to the Rails camp!
Good to know; you first have to reboot your server before you can access those CONSTANTS (go with the flow, use caps for constant variables).
Hi,
Is there way to make this config variable available in a controller? And can you email the answer to me.
Thanks.
Greg
Greg,
Yes this config variable is automatically available to your controllers:
class MyController < ApplicationController
def index
@url = BASE_URL
end
end
I hope this helps.
Regards,
Dennis