Update: A newer version of how I load YAML into configuration files in my projects can be found here.
Since being introduced to YAML I’ve loved using it for configuration files in both Ruby and Ruby on Rails. YAML means “YAML Ain’t Markup Language”. Yes, there is an infinite loop in the title – it’s programmer humor. Those of you familiar with Ruby on Rails are somewhat familiar with YAML because that is the format of the database.yml configuration file. So this is a sample of what a YAML file typically looks like:
development: adapter: mysql database: project_development username: root password: socket: /tmp/mysql.sock
This is a snippet out of the database.yml file. But one of the great things about Ruby is that writing code to read YAML is extremely simple. Let’s say I want to make a website configuration file, this is what that might look like:
config: title: My Rails Website author: Santa Claus email: email@company.com css_file: default.css
The hardest part is thinking about what type of information you want to store in your configuration, the Ruby is extremely easy. Check it out…
First we require the YAML library:
require 'yaml'
Ok, now we can make a read_config method:
def read_config config = YAML.load_file("config.yaml") @title = config["config"]["title"] @author = config["config"]["author"] @email = config["config"]["email"] @css_file = config["config"]["css_file"] end
Seriously, that’s it (of course you need to execute the method). We just load the YAML into a local variable. Then we spider down the YAML document using the local variable that we assigned the loaded YAML document. So where you see “config” in quotes that is referring to the “config:” within the YAML document. Of course, were I say “config.yaml” you would actually put the path to your specific YAML document. One the information is loaded, I pull the data I want into a few instance variables making them accessible to my views (in Rails).
Update:
A more efficient way to do this would be to loop through the hash that is created by the read_config method and just set the key to an instance variable, like so:
config["config"].each { |key, value| instance_variable_set("@#{key}", value) }
Update: A newer version of how I load YAML into configuration files in my projects can be found here.