Created
October 21, 2011 11:30
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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