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

36,263

Solution 1

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

Solution 2

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

Share:
36,263

Related videos on Youtube

mlambie
Author by

mlambie

I like Brazilian jiu jitsu, Xbox, coffee, Lego, comics, knitting, cycling, helicopters, skateboarding and skydiving.

Updated on August 18, 2020

Comments

  • mlambie
    mlambie over 3 years

    In a Ruby on Rails 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.

  • Nikita Rybak
    Nikita Rybak almost 14 years
    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
    Nikita Rybak almost 14 years
    Now that's funny. Who'd know that 'uppercaseness' of those constants is enforced in rails?
  • Adil B
    Adil B about 11 years
    Note: Don't forget to restart your server after making a new constant. Otherwise, it won't show up properly!
  • Simone Carletti
    Simone Carletti about 11 years
    @NikitaRybak it's not because of Rails, it's a requirement of the Ruby language.
  • Crashalot
    Crashalot almost 4 years
    Thanks for the answer! Is this still the best approach for Rails 6? Another answer suggested config.x: stackoverflow.com/a/34053451/144088