Last active
December 29, 2015 10:39
-
-
Save carloslopes/7658120 to your computer and use it in GitHub Desktop.
Ruby Hash to-from dotted notation hash
This file contains hidden or 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
class Hash | |
def to_dotted_hash(recursive_key = '') | |
self.each_with_object({}) do |(k, v), ret| | |
key = recursive_key + k.to_s | |
if v.is_a?(Hash) | |
ret.merge!(v.to_dotted_hash(key + '.')) | |
else | |
ret[key] = v | |
end | |
end | |
end | |
def self.from_dotted_hash(hash, recursive_key = '') | |
key_regexp = /\A(\w+)\./ | |
hash.each_with_object({}) do |(k, v), ret| | |
key = k.gsub(/\A#{recursive_key}/, '') | |
if key =~ key_regexp | |
nested_key = $1 | |
match_nested_hash = ->(k,_) { k.match(/\A#{nested_key}\./) } | |
nested_hash = hash.select(&match_nested_hash) | |
ret.delete_if(&match_nested_hash) | |
ret.merge!(nested_key => from_dotted_hash(nested_hash, nested_key + '.')) | |
else | |
ret[key] = v | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment