Skip to content

Instantly share code, notes, and snippets.

@luki3k5
Created October 21, 2011 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luki3k5/1303609 to your computer and use it in GitHub Desktop.
Save luki3k5/1303609 to your computer and use it in GitHub Desktop.
this is a module that allows flat hash to yaml compatible hash conversions (perfect for spreedsheet to yaml conversion)
# example:
#
# hash = { 'project.name' => "name of the project",
# 'project.date.start' => "start date of the project",
# 'project.date.end' => "end date of the project" }
#
# Spreedsheet2yaml.create_yaml(hash)
#
module Spreedsheet2yaml
@result = {}
def self.hash_from_array(key, arr, main_hash)
current_first = arr.delete_at(0)
return { current_first => hash_from_array(key, arr, main_hash) } if arr.size > 0
return { current_first => main_hash[key] } if arr.size == 0
end
def self.create_yaml(hash)
merger = proc { |key,v1,v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
hash.keys.each do |key|
@result = @result.merge(hash_from_array(key, key.split('.'), hash), &merger)
end
@result.to_yaml
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment