Alex Rivera | Logout

Exact opposite to Ruby's CGI.parse method?

Asked 2011-03-09T12:12:49.277
14

I'd like to do some sanitization of query params.

I parse the query with CGI.parse, then I delete some params, but I can't find an opposite method to build the query.

I don't really want to do something like

params.map{|n,v| "#{CGI.escape n}=#{CGI.escape v.to_s}"}.join("&")

There's got to be a simpler way. Is there?

Edit
Report

1 Answer

3

If you're using Rails (or don't mind pulling in ActiveSupport), then you can use to_param (AKA to_query):

{ :a => '&', :b => 'Where is pancake house?', :c => ['an', 'array'] }.to_param
# a=%26&b=Where+is+pancake+house%3F&c%5B%5D=an&c%5B%5D=array

to_param handles arrays a little differently than your version though, it'll put out c[]=an&c[]=array rather than just c=an&c=array.

answered 2011-03-10T19:01:31.067

Your Answer