That is pretty easy with a plain hash like
{:a => "a", :b => "b"}
which would translate into
"a=a&b=b"
But what do you do with something more complex like
{:a => "a", :b => ["c", "d", "e"]}
which should translate into
"a=a&b[0]=c&b[1]=d&b[2]=e"
Or even worse, (what to do) with something like:
{:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]
Thanks for the much appreciated help with that!
Steal from Merb:
See http://noobkit.com/show/ruby/gems/development/merb/hash/to_params.html
If you are using Ruby 1.9.2 or later, you can use
URI.encode_www_form
if you don't need arrays.E.g. (from the Ruby docs in 1.9.3):
You'll notice that array values are not set with key names containing
[]
like we've all become used to in query strings. The spec thatencode_www_form
uses is in accordance with the HTML5 definition ofapplication/x-www-form-urlencoded
data.There's a much easier way to do this if you're using Rails: http://apidock.com/rails/ActiveSupport/CoreExtensions/Hash/to_query
So you could do:
I know this is an old question, but I just wanted to post this bit of code as I could not find a simple gem to do just this task for me.
Rolled up as gem here: https://github.com/simen/queryparams
For basic, non-nested hashes, Rails/ActiveSupport has
Object#to_query
.http://api.rubyonrails.org/classes/Object.html#method-i-to_query
The best approach it is to use Hash.to_params which is the one working fine with arrays.