1 2 3
require 'uri' uri=URI.parse("http://www.mydomain.com/search?q=foo&bar=stick&who=you") uri_params=uri.query.inject({}) {|hsh,i| sides=i.split("="); hsh[sides[0]]=sides[1]; hsh}
Refactorings
No refactoring yet !
David Calavera
July 10, 2008, July 10, 2008 13:57, permalink
Are you sure that it works? look at my irb output:
>> uri=URI.parse("http://www.mydomain.com/search?q=foo&bar=stick&who=you")
=> #<URI::HTTP:0xfdbdf82f6 URL:http://www.mydomain.com/search?q=foo&bar=stick&who=you>
>> uri_params=uri.query.inject({}) {|hsh,i| sides=i.split("="); hsh[sides[0]]=sides[1]; hsh}
=> {"q"=>"foo&bar"}
zoopzoop
July 10, 2008, July 10, 2008 15:09, permalink
It is this you are trying to do?
1 2 3 4
require 'uri' uri = URI.parse('http://www.mydomain.com/search?q=foo&bar=stick&who=you') uri_params = uri.query.split('&').inject({}) do |hsh, i| kv = i.split('='); hsh[kv[0]] = kv[1]; hsh end #=> {"q"=>"foo", "who"=>"you", "bar"=>"stick"}
Jason Dew
July 10, 2008, July 10, 2008 23:20, permalink
Seems like this should do the job and a little cleaner.
1
Hash[*uri.query.split("&").map {|part| part.split("=") }.flatten]
reima
July 12, 2008, July 12, 2008 21:52, permalink
No need to reimplement functionality already provided by the Standard Library:
1 2 3
require 'cgi' uri = URI.parse("http://www.mydomain.com/search?q=foo&bar=stick&who=you") uri_params = CGI.parse(uri.query)
nakajima
October 16, 2008, October 16, 2008 00:35, permalink
If you just want the query params, here's one.
quick and dirty
1 2 3 4 5
class String query = split(/\?/)[-1] parts = query.split(/&|=/) Hash[*parts] end
grossenidge
June 24, 2009, June 24, 2009 15:59, permalink
Whoever tries some JAgOIbzaCs1P will never be the same again. Remember it friends.
Yury Kotlyarov
August 29, 2010, August 29, 2010 17:32, permalink
I prefer to use addressable gem to work with URIs
1 2 3 4
require 'addressable' uri = Addressable::URI.parse('http://brainhouse.ru/path?aa=bb&cc=dd') uri.query_values #=> { 'aa' => 'bb', 'cc' => 'dd' }
Probably can't be refactored, but I know someday I'll get a code review and someone will say something about this.