Rails: A Question About Constants

Posted on February 5, 2007
Filed Under /dev/ruby | 552 views |

This is one of those questions for which the elegant answer feels like it ought to be simple. In my app I have a module called Constants which contains application-specific constants (such as a copyright notice, for instance).

Putting the constants.rb file into app/helpers and then referencing the constant ala <%= Constants::COPYRIGHT_MESSAGE %> works well enought but feels very inelegant. The need to keep repeating Constants:: irks me.

Is there a better way to include application-wide constants into a Rails app?

Comments

One Response to “Rails: A Question About Constants”

  1. matt on February 12th, 2008 3:31 pm

    I thought this was a pretty good solution:
    http://snippets.dzone.com/posts/show/551

    It doesn’t do anything about repeating “Constants::” but I think it organizes your app more cleanly because it keeps your constants in a YAML file in /config.

    I ended up using this in my environment.rb file, along with “constants.yml” in my /config:

    CONSTANTS = YAML::load(ERB.new((IO.read(”#{RAILS_ROOT}/config/constants.yml”))).result).symbolize_keys

Leave a Reply