Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact opposite to Ruby's CGI.parse method?

Tags:

ruby

cgi

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?

like image 455
Leonid Shevtsov Avatar asked Mar 09 '11 12:03

Leonid Shevtsov


People also ask

Is Ruby a CGI?

rb. Ruby comes with a special library called cgi that enables more sophisticated interactions than those with the preceding CGI script. Here, you created a CGI object and used it to print the header line for you.

What is CGI escaped?

CGI. escape is for escaping a URL value in the query string.

What is CGI in rails?

The Common Gateway Interface (CGI) is a simple protocol for passing an HTTP request from a web server to a standalone program, and returning the output to the web browser.


3 Answers

There is a nice method in URI module:

require 'uri'
URI.encode_www_form("q" => "ruby", "lang" => "en")  #=> "q=ruby&lang=en"
like image 97
ujifgc Avatar answered Oct 29 '22 16:10

ujifgc


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.

like image 39
mu is too short Avatar answered Oct 29 '22 14:10

mu is too short


While there's no better answer, I'll put up the method which I'm 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
like image 2
Leonid Shevtsov Avatar answered Oct 29 '22 15:10

Leonid Shevtsov