[Rails] Configuration values

Marcel Molina Jr. marcel at vernix.org
Wed Jan 5 01:35:59 GMT 2005


On Tue, Jan 04, 2005 at 03:29:36PM -0800, Sean Leach wrote:
> I read this wiki entry:
> 
> http://wiki.rubyonrails.com/rails/show/HowtoUseConfigurationFiles
> 
> and I think I am more confused now about application config variables.
> 
> I want to have values that are different for development and production,
> for example
> 
> @app_config['path']['upload_path']
> @app_config['main']['prefix']
> 
> etc. accessible in my controllers, views etc.  What is the common way of
> doing this?  i.e. it seems logical I would put this in
> config/development.yml etc., and there would be a common way to access
> this information.

As the page explains you can create a set of yaml files in your config
directory. Since you say you want separate values for each environment then
you could create a config/development.yml and config/production.yml as you
proposed above.

The config/environment.rb file is evaluated no matter what environment
you are running under but then in config/environments there are files for
each environment which are used to set per environment configuration. The
config/environment.rb file loads the appropriate file depending on which
environment you are running under. As the wiki page explains you could
use those files to define a method which just returns the appropriate
yaml file slurped up into a ruby data structure.

So if you had a file config/development.yml with the following:

    main:
        prefix: zip

    paths:
        uploads: /dev/null

And in your config/environments/development.rb you had:

    def app_configurations
      YAML.load(File.open(RAILS_ROOT + '/config/development.yml'))
    end

Then when you were running in the development environment and you called
app_configurations you'd get:
    
    {"paths"=>{"uploads"=>"/dev/null"}, "main"=>{"prefix"=>"zip"}}

So app_configurations['paths']['uploads'] would return "/dev/null"

Do something similar for your production and testing and you should be all
set.

The thing that makes this configuration data structure available to you need
to be a method, per se. You could alternatively make it a CONSTANT.

e.g

    APP_CONFIG = YAML.load(File.open(RAILS_ROOT + '/config/development.yml'))

FYI you can't name it Config though as that clashes with a constant set in
TMail. I'd just stick with a method in any event.

marcel
-- 
Marcel Molina Jr. <marcel at vernix.org>


More information about the Rails mailing list