Go Configure...
2009/11/11 // Leeds // // Feed
Its handy to keep common configuration values inside a single file. This is nothing new and people have been doing something like this in Rails apps for quite some time:
CONFIG = YAML.load_file(RAILS_ROOT + "config/settings.yml")
Whilst this is perfectly fine its not the nicest to use across your app. To me it doesn’t look very pretty when accessing the values.
Given the following YAML file:
meta:
keywords: "my, app, keywords"
description: "My apps description."
Accessing these values using the above method would look like this:
CONFIG["meta"]["description"]
I wanted to scratch this itch, so I made a quick and dirty plugin to solve the issue. I wanted to be able to access the values easier and have them available within all of my models, mailers, views and controllers. I also wanted the plugin to auto load once dropped into a Rails project.
To make things even easier I also wanted a Rake task to copy the YAML files into the config/ directory. Although this is a trivial job, this would help to automate the installation process when using Rails templates.
Using the plugin is simple. Once installed, enter some configuration values into a YAML file as normal. Then access the values from within this file within your app like this:
c(:meta, :keywords)
The plugin will try to load config/environment.yml and config/environments/RAILS_ENV.yml if they exist. To install these files automatically simply enter rake configurable:install to copy over the default files:
>> Added configuration files: + config/environment.yml + config/environments/development.yml + config/environments/staging.yml + config/environments/production.yml
If you want to extend the plugin to be accessible in other areas of your application, you can add another hook into the self.setup method located in lib/configurable/configuration.rb:
# lib/configurable/configuration.rb
def self.setup(files)
# ... code omitted
# Add any other classes you may want the plugin to be available in below:
MyClass::Base.send :include, Helpers
end
The codes nothing impressive and its a tiny plugin but its one of those things thats been annoying me for a while.
Get the code:
- » Directly from GIT
git://github.com/joshnesbitt/configurable.git.- » From the Github repository http://github.com/joshnesbitt/configurable.