Transform a flat hash to a structured hash using template.
gem install hash_template
require 'hash_template'
require 'pp'
data = {
address: 'milton.waddams@initech.com',
password: 'No salt',
first_name: 'Milton',
last_name: 'Waddams',
department: 'Reporting',
title: 'Collator',
privacy: true,
org_unit_path: '/BasementDwellers'
}
mapping = {
primaryEmail: :address,
password: :password,
name: {
givenName: :first_name,
familyName: :last_name
},
organizations: [
{
department: :department,
title: :title
}
],
includeInGlobalAddressList: '!privacy',
orgUnitPath: 'org_unit_path'
}
pp HashTemplate.new(mapping).map(data)
#{
# primaryEmail: 'milton.waddams@initech.com',
# password: 'No salt',
# name: {
# givenName: 'Milton',
# familyName: 'Waddams'
# },
# organizations: [
# {
# department: 'Reporting',
# title: 'Collator'
# }
# ],
# includeInGlobalAddressList: false,
# orgUnitPath: '/BasementDwellers'
#}
Inspired by Adam Crownoble's article: Transforming Hashes: A Refactoring Story
For backward transformation use hash_map_hash gem.
MIT.