SitePoint Sponsor |
|
User Tag List
Results 1 to 6 of 6
Thread: Inverse of CGI.parse
-
Dec 5, 2008, 04:53 #1
- Join Date
- Jun 2004
- Location
- Copenhagen, Denmark
- Posts
- 6,157
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Inverse of CGI.parse
CGI.parse takes a querystring and returns a hash. I'm looking for a way to do the inverse. Any suggestions?
-
Dec 6, 2008, 01:43 #2
- Join Date
- Feb 2007
- Posts
- 270
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
given "hash" as a hash, try hash.to_query and see if that's what you're looking for.
-
Dec 8, 2008, 03:15 #3
- Join Date
- Jun 2004
- Location
- Copenhagen, Denmark
- Posts
- 6,157
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Close, but not quite. CGI.parse gives back an array of values, even when there is just one. to_query interprets this as the value being present multiple times. I just wrote my own implementation, but if a standard solution existed, I would have preferred to use that.
-
Dec 9, 2008, 02:33 #4Code:
my_hash.map { |key, value| "#{key}=#{CGI.escape(value)}" }.join('&')
Ohai!
-
Dec 10, 2008, 15:19 #5
- Join Date
- Jun 2004
- Location
- Copenhagen, Denmark
- Posts
- 6,157
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Not quite. The result from CGI.parse looks like this:
Code:irb(main):002:0> CGI.parse "foo=42&bar[]=1&bar[]=2&bar[]=3" => {"bar[]"=>["1", "2", "3"], "foo"=>["42"]}
-
Dec 11, 2008, 06:49 #6
- Join Date
- Jun 2004
- Location
- Copenhagen, Denmark
- Posts
- 6,157
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Just in case somebody else needs this, here's the code I came up with:
Code:require 'uri' def hash_to_query(h) h.map do |k, v| v.map do |value| (value.nil?) ? URI.encode(k.to_s) : "%s=%s" % [URI.encode(k.to_s), URI.encode(value.to_s)] end end.flatten.join("&") end
Bookmarks