Created
November 7, 2008 05:56
-
-
Save delano/22789 to your computer and use it in GitHub Desktop.
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
# uri_params | |
# | |
# Turn URI parameters like uri[0], uri[1]... into an array of values | |
# and ones like account[id], account[name]... into a hash | |
# This needs to be called inside of a "post" or "get" command. It doesn't work when placed inside the "before" (?) | |
def uri_params_fix! | |
p = params | |
p.each_pair do |key_with_index, value| | |
next unless (match = key_with_index.to_s.match(/(.+)\[['"]?([\w\-]+)['"]?\]/)) | |
key = match[1].to_s # The first match will be the key name (ie "uri") | |
index = match[2] # And the second match is the index (ie "0" or "name") | |
# This index is numeric (for an array) | |
if index[/\d+/] | |
# This is ugly but the idea is to preserve an existing value. For example, | |
# uri=something and uri[0]=another become uri=['something','another'] | |
p[key] = (p[key]) ? [p[key]] : [] unless p[key].is_a? Array | |
p[key] << value | |
# and this index is a string (for a hash) | |
else | |
# Again, ugly but it's for preserving an existing value | |
p[key] = (p[key]) ? {p[key] => p[key]} : {} unless p[key].is_a? Hash | |
p[key][index.to_s] = value | |
end | |
# Remove the [1] or [name] from the params | |
p.delete(key_with_index) | |
end | |
params = p | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment