Created
December 7, 2011 17:29
-
-
Save andrewheins/1443695 to your computer and use it in GitHub Desktop.
QueryString to Hash in Ruby
This file contains hidden or 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(querystring) | |
keyvals = query.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. |
typo bro. line 6. :)
this works also.
CGI.parse(URI.parse(url).query)
CGI.parse(URI.parse(url).query)
is not the same:
url = 'https://google.com?q=success'
CGI.parse(URI.parse(url).query)
#=> {"q"=>["success"]}
CGI.unescape CGI.parse(URI.parse(url).query).to_query
#=> "q[]=success"
use rails activesupport's to_query and rack parse_nested_query
query_string = CGI.unescape(hash.to_query) hash = Rack.parse_nested_query(query_string)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In line 6, in the passing parameter, i think you mean "querystring" intead of "query".
Cheers!