Last active
August 29, 2015 14:07
-
-
Save crawsible/72d35df9023f655cac8d to your computer and use it in GitHub Desktop.
parsing string formatted as rails-style nested params Hash
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
def parse_www_encoded_form(www_encoded_form) | |
URI.decode_www_form(www_encoded_form).each do |pair| | |
# returns array of names between '[' and ']' characters | |
key_parts = pair.first.split(/\]\[|\[|\]/) | |
current_hash = @params | |
new_key = key_parts.shift | |
# this does not run unless key_parts.count > 1 | |
until key_parts.empty? do | |
# point current hash to hash at current_hash[new_key]. If | |
# current_hash[new_key] is nil, set it (and current_hash) to {} | |
current_hash = current_hash[new_key] ||= {} | |
# grab the next key_part | |
new_key = key_parts.shift | |
end | |
# the final key is paired in the deepest-nested hash | |
# with the actual value | |
current_hash[new_key] = pair.last | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment