-
-
Save millisami/5966043 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
# Today's little useless tidbit converts a url's query string into a hash | |
# set of k/v pairs in a way that merges duplicates and massages empty | |
# querystring values | |
def qs_to_hash(query_string) | |
keyvals = query_string.split('&').inject({}) do |result, q| | |
k,v = q.split('=') | |
if !v.nil? | |
result.merge({k => v}) | |
elsif !result.key?(k) | |
result.merge({k => true}) | |
else | |
result | |
end | |
end | |
keyvals | |
end | |
qs_to_hash("a=b&b=c&c=d") # {a=>b, b=>c, c=>d} | |
qs_to_hash("a=b&b=c&c") # {a=>b, b=>c, c=>true} nil becomes true | |
qs_to_hash("a=b&b=c&a=d") # {a=>d, b=>c} last declaration wins | |
qs_to_hash("a=b&b=c&a") # {a=>b, b=>c} nils don't override set vals | |
# Now, of course Rails's implementation is much smarter than this... | |
# but you never know. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment