Search code examples
rubyhttpparametershashmap

Ruby: How to turn a hash into HTTP parameters?


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!


Solution

  • Update: This functionality was removed from the gem.

    Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.

    require "addressable/uri"
    uri = Addressable::URI.new
    uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
    uri.query
    # => "a=a&b[0]=c&b[1]=d&b[2]=e"
    uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
    uri.query
    # => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
    uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
    uri.query
    # => "a=a&b[c]=c&b[d]=d"
    uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
    uri.query
    # => "a=a&b[c]=c&b[d]"
    uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
    uri.query
    # => "a=a&b[c]=c&b[d]"
    

    The gem is 'addressable'

    gem install addressable