A clean and simple way to manage your application's per-environment constants
Switch branches/tags
Nothing to show
Clone or download
Pull request Compare This branch is 2 commits ahead, 31 commits behind leonardoborges:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


Note for Rails 2.3.x users

Check out the branch rails_2_3_x.

Master is Rails 3 compatible only.


It's funny how every Rails application I work on ends up needing some sort of per-environment global constants.

Examples may include the application url - It might be used in account activation emails and thus should be different between the development and production environments.

Or perhaps your application depends on external services that, depending on the environment, are available in different URIs.

One common approach is to define these constants in your environment files:

# in environment.rb
Rails::Initializer.run do |config|
  ACTIVATION_URL = "http://www.example.com/activate"

#and then in development.rb
  ACTIVATION_URL = "http://localhost:3000/activate"

But in my experience constants end up being scattered all around, people don't know where to look for them and much less where new ones should be defined.

AppConstants is a very simple plugin that provides a clean way to handle this need. Go ahead, install the plugin and run generator:

$ rails plugin install git://github.com/leonardoborges/app_constants.git

$ rails generate app_constants
  exists  config
  create  config/constants.yml
  exists  config/initializers
  create  config/initializers/load_app_constants.rb

Now use the constants.yml file to define your own constants and the load_app_constants.rb initializer to customize the plugin. e.g: Change the default location for the constants.yml file.


If you have a constants.yml file that looks like this:

# Enter your per-environment constants below

development: &default
  activation_url:  "http://localhost:3000/activate"

  <<: *default
  activation_url:  "http://www.example.com/activate"

Then you can use the AppConstant class to retrieve your constants anywhere in your app:

# somewhere in the activation email view
Visit this url to activate your account:
  <%= "#{AppConstants.activation_url}/#{activation_code}" %>

Copyright © 2010 Leonardo Borges, released under the MIT license