Where’s the best place to define a constant in a Ruby on Rails application?

Rails >= 3, the application is itself a module (living in config/application.rb). You can store them in the application module

module MyApplication
  SUPER_SECRET_TOKEN = "123456"
end

Then use MyApplication::SUPER_SECRET_TOKEN to reference the constant.


Rails >= 2.1 && < 3 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

Leave a Comment