Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to store globals in Rails app?

I was wondering if there is the best practice on where to store global settings in a rails app. What I mean by that is i.e: I have a few globals defined that may change, but not likely and it seems inappropriate to store them in DB since they are used so much. For instance I have SYSTEM_EMAIL & SYSTEM_EMAIL_SIGNATURE & SYSTEM_STORAGE_ROOT.

Right now I keep them in environment.rb, but I'm not sure if this is the right palce to store them.

Thank you

EDIT:

Accepted answer still stands as appropriate, however I since moved on to using https://github.com/markbates/configatron , there are other options but I like configatron the most.

like image 796
konung Avatar asked Apr 19 '10 21:04

konung


1 Answers

One of my favourite techniques is to put a file containing the constants in directory config/initializers/ (all files in this directory are loaded automatically) but with a section for each different Rails environment. e.g.


case ENV['RAILS_ENV']
  when "development"
    SYSTEM_EMAIL = ...
    SYSTEM_EMAIL_SIGNATURE = ...
  when "staging"
    SYSTEM_EMAIL = ...
    SYSTEM_EMAIL_SIGNATURE = ...
  when "production"  
    SYSTEM_EMAIL = ...
    SYSTEM_EMAIL_SIGNATURE = ...
end

If you want, instead, to load up all the constants in one big hash then you can load them as a YAML file. Create two files, one called, say, config/initializers/email_constants.rb and the other config/email_constants.yml. In the latter put something like:


development:
  :system_email: ...
  :system_email_signature: ...
staging:
  :system_email: ...
   system_email_signature: ...

... etc ...

Then in config/initializers/email_constants.rb put:


EMAIL_CONSTANTS = YAML.load_file("#{RAILS_ROOT}/config/email_constants.yml")[RAILS_ENV]

This loads the entire YAML file and the assigns the value of the appropriate key (which represents the RAILS_ENV) to EMAIL_CONSTANTS.

The advantage of both of these techniques is locality. You can place all the constants that are related to each other (i.e. email constants in this case) in one file. Also, instead of having the same constants spread across three different files (one for each Rails environment) you have them all in one file.

like image 178
Sean Seefried Avatar answered Oct 07 '22 17:10

Sean Seefried