Exactly against the Ruby CGI.parse method?

I would like to do some sanitization of the request parameters.

I parse the request using CGI.parse , then I delete some parameters, but I cannot find the opposite method to build the request.

I really don't want to do something like

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

There should be an easier way. There is?

+8
ruby cgi
source share
4 answers

Until there is a better answer, I will put the method that I am using now.

 def build_query(params) params.map do |name,values| values.map do |value| "#{CGI.escape name}=#{CGI.escape value}" end end.flatten.join("&") end 
+2
source share

There is a good method in the URI module:

 require 'uri' URI.encode_www_form("q" => "ruby", "lang" => "en") #=> "q=ruby&lang=en" 
+5
source share

If you use Rails (or don't mind pasting ActiveSupport), 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 treats arrays a little differently than your version, but instead of c=an&c=array c[]=an&c[]=array will be placed.

+3
source share

I am not sure what the following simplification is, but this avoids expanding the hash pair (key, value).

 params.map{|qq| qq.map{|q| CGI.escape(q)}.join('=')}.join('&') 
0
source share

All Articles