Skip to content

Instantly share code, notes, and snippets.

@crawsible
Last active August 29, 2015 14:07
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 crawsible/72d35df9023f655cac8d to your computer and use it in GitHub Desktop.
Save crawsible/72d35df9023f655cac8d to your computer and use it in GitHub Desktop.
parsing string formatted as rails-style nested params Hash
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