开发者

How to concatenate a Hash to URL parameters?

开发者 https://www.devze.com 2022-12-10 01:07 出处:网络
a quick Ruby question for you: params = {:q => \"A query\",:foo => \"bar\",:nasty => \"Schrödinger\'s cat\"}

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+ca开发者_如何学Got

(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?


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's cat"}

params.to_param 
=> "foo=bar&nasty=Schr%C3%B6dinger%27s+cat&q=A+query" 


Rails does this 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 decoded would be: "?ids[]=1&ids[]=2&query=cheese"


You can make it a little bit simpler using collect:

def do_it(params)
  params.collect do |key,val|
    "#{CGI.escape(key.to_s)}=#{CGI.escape(val)}"
  end.join('&')
end

I don't know how much more you can simplify it than that. Also, note that CGI.escape will converts spaces into +, not %20. If you really want %20, use URI.escape instead (you'll have to require 'uri', obviously).


I agree that this is very "un-ruby-like" code. Although it's not much better, I think requestify() may 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 rails documentation. Do not forget to read the comments above the method definition.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号