In a Ruby on Rails 2.3.2 application, where is the best place to define a constant?
I have an array of constant data that I need available across all the controllers in my application.
In a Ruby on Rails 2.3.2 application, where is the best place to define a constant?
I have an array of constant data that I need available across all the controllers in my application.
You can place them in config/environment.rb:
Rails::Initializer.run do |config|
...
SITE_NAME = 'example.com'
end
If you have large amounts of global constants, this can be messy. Consider sourcing from a YAML file, or keeping the constants in the database.
EDIT:
weppos' answer is the better answer.
Keep your constants in a file in config/initializers/*.rb
This article from Tim Lucas outlines a really neat way of defining application constants.
As of Rails >= 2.1 you should place them
/config/initializers
when the constant has the applications scopePrior to Rails 2.1 and initializers
support, programmers were used to place application constants in environment.rb.
Here's a few examples
# config/initializers/constants.rb
SUPER_SECRET_TOKEN = "123456"
# helpers/application_helper.rb
module ApplicationHelper
THUMBNAIL_SIZE= "100x20"
def thumbnail_tag(source, options = {})
image_tag(source, options.merge(:size => THUMBNAIL_SIZE)
end
end