Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a Hash to URL parameters?

Tags:

url

ruby

a quick Ruby question for you:

params = {:q => "A query",:foo => "bar",:nasty => "Schrödinger's cat"}
p do_it(params)
=> q=A%20query&foo=bar&nasty=Schr%C3%B6dinger%27s+cat

(I think ö encodes like that, excuse me if its wrong) Is there a simpler way to do this than the following?:

def do_it(params)
  out = []
  params.each_pair{|key,val|
    out.push "#{CGI.escape(key.to_s)}=#{CGI.escape(val)}"
  }
  out.join("&")
end

I'm not looking to start a war over the 'best' way to do this - its just this method seems very kludgey and un-ruby like! Any tips?

like image 465
JP. Avatar asked Nov 04 '09 14:11

JP.


People also ask

What is Param hash?

The hash parameter allows you to prepare REST requests that can be executed by unauthenticated users. Requests that contain the hash parameter ignore the credentials specified in the authentication header. To get the authentication hash for REST requests: Prepare the URL of your REST request in advance.

What is hash and query string?

A query string hash (QSH) is an important technique to prevent URL tampering and secure HTTP requests when they are made via a browser. The QSH secures the HTTP method, the relative URI path, and the query string parameters.


1 Answers

Here's a shorter and more efficient method.

def parameterize(params)
  URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))
end
like image 148
Michael Richards Avatar answered Oct 19 '22 19:10

Michael Richards