views:

27

answers:

2

I am using a YAML file for configuration in my rails app and a few entries in the file are subsets of future entries, eg -

domain: domain.com
name: jack
email: [email protected]

To make this more efficient, is something like this possible in YAML ?

domain: domain.com
name: jack
email: jack@${domain}

A: 

YAML has anchors, but you can't quite use them as variables the way you did in your question. You can get close with a post-processing step. Say your domains.yaml is

domains:
  - domain: &domain domain.com
    name: jack
    emaillocal: jack
    emaildomain: *domain

  - domain: &domain thehill.com
    name: Jill
    emaillocal: jill
    emaildomain: *domain

Then with

#! /usr/bin/ruby

require "yaml"

yaml = YAML.load_file('domains.yaml')

yaml['domains'].each { |d|
  d['email'] = d['emaillocal'] + '@' + d['emaildomain']
}

puts YAML::dump(yaml)

you get

domains: 
- name: jack
  emaildomain: domain.com
  domain: domain.com
  emaillocal: jack
  email: [email protected]
- name: Jill
  emaildomain: thehill.com
  domain: thehill.com
  emaillocal: jill
  email: [email protected]
Greg Bacon