Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@choncou
Created July 8, 2019 16:13
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 choncou/57348f90e7559737ee030448a7aac5ff to your computer and use it in GitHub Desktop.
Save choncou/57348f90e7559737ee030448a7aac5ff to your computer and use it in GitHub Desktop.
Hash from dot-notation keys
def hash_from_dot_notation(value)
return value unless value.is_a?(Hash)
value.deep_stringify_keys.each_with_object({}) do |(k,v), result|
root, child = k.split('.')
if child
result[root] ||= {}
result[root][child] = hash_from_dot_notation(v)
else
result[root] = hash_from_dot_notation(v)
end
end
end
@choncou
Copy link
Author

choncou commented Jul 8, 2019

# Used to convert a hash with keys that are dot-notation into nested values
# Eg:
# params = {
#   "legalType"=>"PRIVATE",
#   "abartn"=>"111000025",
#   "accountNumber"=>"1234567",
#   "accountType"=>"CHECKING",
#   "address.city"=> {
#     'param.name'=>'Durban',
#     'param.code'=>'DBN'
#   },
#   "details"=> {
#     "account_details_type"=>"aba",
#     "address.country"=>"EH",
#     "address.city"=>"London",
#     "address.postCode"=>"10025",
#     "address.firstLine"=>"50 Branson Ave"
#   }
# }

# hash_from_dot_notation(params)

# {
#   "legalType"=>"PRIVATE",
#   "abartn"=>"111000025",
#   "accountNumber"=>"1234567",
#   "accountType"=>"CHECKING",
#   "address"=>{
#     "city"=>{
#       "param"=>{"name"=>"Durban", "code"=>"DBN"}
#     }
#   },
#   "details"=>
#   {
#     "account_details_type"=>"aba",
#     "address"=>
#     {
#       "country"=>"EH",
#       "city"=>"London",
#       "postCode"=>"10025",
#       "firstLine"=>"50 Branson Ave"
#     }
#   }
# }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment