views:

1626

answers:

3

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.

+2  A: 

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

guns
A: 

This article from Tim Lucas outlines a really neat way of defining application constants.

mlambie
+6  A: 

As of Rails >= 2.1 you should place them

  1. in /config/initializers when the constant has the applications scope
  2. when the constant refers to a specific model/controller/helper you can scope it within the class/module itself

Prior 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
Simone Carletti
strange, but doesn't work. Although constants.rb is executed on launch, I can't access SUPER_SECRET_TOKEN in controllers or views.
Nikita Rybak
Now that's funny. Who'd know that 'uppercaseness' of those constants is enforced in rails?
Nikita Rybak