I'm not very superstitious. Some of my favorite pieces of fiction are full of the supernatural because I know that, in the real world, magic is just what the ignorant call what they don't understand. Magic is relative, in a way. i rid my world of a little bit of magic today, and in exchange, I gained a whole world of knowledge as to what goes behind the scenes in Rails.
Building my own Rails methods (solo!) in Ruby did wonders to my understanding of what exactly each method is doing. The hardest part was creating my own params. It's all peachy when there's only one layer, but what do you do when you have user[address][street]=main&user[address][zip]=89436 and you want to turn it into { "user" => { "address" => { "street" => "main", "zip" => "89436" } } }?
Well, first I needed a helper method to get all of the keys available:
def parse_key(key)
key.split(/\]\[|\[|\]/)
end
The URI class has a pretty cool method in Ruby called #decode_www_form which takes a query string such as “a=1&a=2&b=3” and returns an array [‘a’, ‘1’], [‘a’, ‘2’], [‘b’, ‘3’].
Knowing this, I took the original user[address][street]=main&user[address][zip]=89436 string, passed it through #decode_www_form, and for each pair, begin nesting:
def parse_www_encoded_form(www_encoded_form)
nested_hash = {}
URI.decode_www_form(www_encoded_form).each do |pair|
array_of_keys = parse_key(pair[0])
level_hash = nested_hash
while array_of_keys.length > 1
unless level_hash.keys.include?(array_of_keys.first)
level_hash[array_of_keys.first] = {}
end
level_hash = level_hash[array_of_keys.first]
array_of_keys.shift
end
level_hash[array_of_keys.first] = pair[1]
end
@params.merge!(nested_hash)
end
I want to go back and redo this method. It's too long. It needs to be broken down. And I am pretty sure there's a way of doing this recursively with a helper method. Pretty much, until parse_key(query) == query, keep nesting. Thursday is a catch-up day, after our 2.5 hour assessment where we write our own authorization, so I'll find the time.