Best place for global (or semi-global) constants.

Hi all,

I was wondering where the best place is to put global values, such as consts? Is environment.rb a good (and kosher) place? Or should I place them in the ApplicationHelper, some custom global helper, or other?

When I said semi-global I guess I was referring to strings, const ints, etc. which may be shared between two or more controller/views. I'm guessing in this scenario placing them in a helper is the best solution?

Thoughts?

Thanks.

Cheers, Diego

Hi!

Have a read here: http://toolmantim.com/article/2006/12/27/environments_and_the_rails_initialisation_process

The various config hooks are a pretty good place for global stuff. For the "semi-global" case, I normally create a module named after my app and place these things in there, with defaults. I can then override defaults in environment.rb.

Cheers, --max

Thoughts?

I put all global stuff in (of course) config/environment.rb. These are the settings that are consistent across dev, test and production environments. I then have a config/constants.rb that are application specific and may be modified as features are added/modified. I load it by adding the following line in config/envrionment.rb:

require File.join(File.dirname(FILE), ‘constants’)

I ignore the environment.rb from the svn repository so it doesn’t get updated and therefore won’t be overridden with an svn update. Some items such as an ENCRYPTION_SALT constant would be different on a test box than the production box and should go in environment.rb. Production may also be running a different RAILS_GEM_VERSION, so we wouldn’t want to accidentally update that setting.

Other application constants and some methods on those constants I put in constants.rb . I add them here because no manual work needs to be done to update the environment.rb. And the application gets these updates with a deploy.

It’s a simple solution that has worked and I haven’t had any issues.

Hope this helps, andy

Diego,

I find it clearer to namespace my application constants in environment.rb.

# environment.rb ... module COOL_APP   VERSION = 1.1 end

Then in your application:

COOL_APP::VERSION

We also use environment.rb

I second the namespacing in config/environment.rb. That added level of safety that the module gives helps me sleep at night knowing I won’t be breaking Rails’ code or that of any plugins/gems/etc. Provided I create a unique module name and not something like Rails. :wink:

RSL

I use an app_name.rb in lib/ contaning:

module AppName

CONSTANT = 1

end

Hi all,

I was wondering where the best place is to put global values, such as consts? Is environment.rb a good (and kosher) place? Or should I place them in the ApplicationHelper, some custom global helper, or other?

Adding them to an active-record-model that is loaded when it's requested is also an idea, which I use myself...

With a class-method you can get the class from the db, and pass on the method-call: