Avatar

Probably can't be refactored, but I know someday I'll get a code review and someone will say something about this.

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 !

0c39b828636367fc6e22b7be8c803c74

David Calavera

July 10, 2008, July 10, 2008 13:57, permalink

No rating. Login to rate!

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"}

Eed31d42c365b4216a6551c7bef2437d

zoopzoop

July 10, 2008, July 10, 2008 15:09, permalink

2 ratings. Login to rate!

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"}
D16d53391068ff0830269149b060789d

Jason Dew

July 10, 2008, July 10, 2008 23:20, permalink

2 ratings. Login to rate!

Seems like this should do the job and a little cleaner.

1
Hash[*uri.query.split("&").map {|part| part.split("=") }.flatten]
Avatar

reima

July 12, 2008, July 12, 2008 21:52, permalink

2 ratings. Login to rate!

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)
Eed31d42c365b4216a6551c7bef2437d

zoopzoop

July 13, 2008, July 13, 2008 07:03, permalink

No rating. Login to rate!

Good catch, reima!

3399cbfb9e5fec93c324789b29309911

nakajima

October 16, 2008, October 16, 2008 00:35, permalink

1 rating. Login to rate!

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
96c5a259a5ae03cd0e770ea7a2dde3bf

grossenidge

June 24, 2009, June 24, 2009 15:59, permalink

No rating. Login to rate!

Whoever tries some JAgOIbzaCs1P will never be the same again. Remember it friends.

94ef1c99f4d4567563f576783979804f

Yury Kotlyarov

August 29, 2010, August 29, 2010 17:32, permalink

No rating. Login to rate!

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' }

Your refactoring





Format Copy from initial code

or Cancel