convert ruby hash to URL query string … without th

2019-03-26 03:34发布

In Python, I can do this:

>>> import urlparse, urllib
>>> q = urlparse.parse_qsl("a=b&a=c&d=e")
>>> urllib.urlencode(q)
'a=b&a=c&d=e'

In Ruby[+Rails] I can't figure out how to do the same thing without "rolling my own," which seems odd. The Rails way doesn't work for me -- it adds square brackets to the names of the query parameters, which the server on the other end may or may not support:

>> q = CGI.parse("a=b&a=c&d=e")
=> {"a"=>["b", "c"], "d"=>["e"]}
>> q.to_params
=> "a[]=b&a[]=c&d[]=e"

My use case is simply that I wish to muck with the values of some of the values in the query-string portion of the URL. It seemed natural to lean on the standard library and/or Rails, and write something like this:

uri = URI.parse("http://example.com/foo?a=b&a=c&d=e")
q = CGI.parse(uri.query)
q.delete("d")
q["a"] << "d"
uri.query = q.to_params # should be to_param or to_query instead?
puts Net::HTTP.get_response(uri)

but only if the resulting URI is in fact http://example.com/foo?a=b&a=c&a=d, and not http://example.com/foo?a[]=b&a[]=c&a[]=d. Is there a correct or better way to do this?

5条回答
一夜七次
2楼-- · 2019-03-26 03:45

In modern ruby this is simply:

require 'uri'
URI.encode_www_form(hash)
查看更多
▲ chillily
3楼-- · 2019-03-26 03:46

As a simple plain Ruby solution (or RubyMotion, in my case), just use this:

class Hash
  def to_param
    self.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
  end
end

{ fruit: "Apple", vegetable: "Carrot" }.to_param # => "fruit=Apple&vegetable=Carrot"

It only handles simple hashes, though.

查看更多
干净又极端
4楼-- · 2019-03-26 04:02

The way rails handles query strings of that type means you have to roll your own solution, as you have. It is somewhat unfortunate if you're dealing with non-rails apps, but makes sense if you're passing information to and from rails apps.

查看更多
Luminary・发光体
5楼-- · 2019-03-26 04:03

Here's a quick function to turn your hash into query parameters:

require 'uri'
def hash_to_query(hash)
  return URI.encode(hash.map{|k,v| "#{k}=#{v}"}.join("&"))
end
查看更多
做个烂人
6楼-- · 2019-03-26 04:06

Quick Hash to a URL Query Trick :

"http://www.example.com?" + { language: "ruby", status: "awesome" }.to_query

# => "http://www.example.com?language=ruby&status=awesome"

Want to do it in reverse? Use CGI.parse:

require 'cgi' 
# Only needed for IRB, Rails already has this loaded

CGI::parse "language=ruby&status=awesome"

# => {"language"=>["ruby"], "status"=>["awesome"]} 
查看更多
登录 后发表回答