How to combine Hash parameters in URL?
quick Ruby request for you:
params = {:q => "A query",:foo => "bar",:nasty => "Schrödinger cat"} p do_it(params) => q=A%20query&foo=bar&nasty=Schr%C3%B6dinger%27s+cat (I think ö is encoded like this, sorry if it's wrong) Is there an easier 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 going to start a war for the “best” way to do this - its just this method seems very kludgey and un-ruby like it! Any tips?
Here's a shorter and more efficient method.
def parameterize(params) URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&')) end use .to_param
params = {:q => "A query",:foo => "bar",:nasty => "Schrödinger cat"} params.to_param => "foo=bar&nasty=Schr%C3%B6dinger%27s+cat&q=A+query" Rails does it for you.
params = {:ids => [1,2], :query => 'cheese'} out = ActionController::Routing::Route.new.build_query_string(params) => "?ids%5B%5D=1&ids%5B%5D=2&query=cheese" which would be decoded: "? ids [] = 1 & amids; id [] = 2 & query = cheese"
You can make this a little easier by using collect :
def do_it(params) params.collect do |key,val| "#{CGI.escape(key.to_s)}=#{CGI.escape(val)}" end.join('&') end I do not know how much more you can simplify it. Also note that CGI.escape converts spaces to + , not %20 . If you really want %20 , use URI.escape instead (you'll have to require 'uri' , obviously).
I agree that this is a very "non-ruby-like" code. Although this is not much better, I think requestify () might be what you want:
http://www.koders.com/ruby/fid4B642EE4A494A744ACC920A1BE72CFE66D1D2B97.aspx?s=cgi#L291
You should probably try following
def to_query(key) "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" end copied from rail documentation . Remember to read the comments above the method definition.