Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

A clean and simple way to manage your application's per-environment constants

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 tasks
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 MIT-LICENSE
Octocat-spinner-32 README.rdoc
Octocat-spinner-32 Rakefile
Octocat-spinner-32 app_constants.gemspec
README.rdoc

Note for Rails 2.3.x users

Check out the branch rails_2_3_x.

Master is Rails 3 compatible only.

AppConstants

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"
end

#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.

Example

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"

production:
  <<: *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

Something went wrong with that request. Please try again.