Ruby: How to turn a hash into HTTP parameters?

后端 未结 14 1609
故里飘歌
故里飘歌 2020-12-07 06:46

That is pretty easy with a plain hash like

{:a => \"a\", :b => \"b\"} 

which would translate into

\"a=a&b=b\"
<         


        
14条回答
  •  感动是毒
    2020-12-07 07:52

    No need to load up the bloated ActiveSupport or roll your own, you can use Rack::Utils.build_query and Rack::Utils.build_nested_query. Here's a blog post that gives a good example:

    require 'rack'
    
    Rack::Utils.build_query(
      authorization_token: "foo",
      access_level: "moderator",
      previous: "index"
    )
    
    # => "authorization_token=foo&access_level=moderator&previous=index"
    

    It even handles arrays:

    Rack::Utils.build_query( {:a => "a", :b => ["c", "d", "e"]} )
    # => "a=a&b=c&b=d&b=e"
    Rack::Utils.parse_query _
    # => {"a"=>"a", "b"=>["c", "d", "e"]}
    

    Or the more difficult nested stuff:

    Rack::Utils.build_nested_query( {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}] } )
    # => "a=a&b[][c]=c&b[][d]=d&b[][e]=e&b[][f]=f"
    Rack::Utils.parse_nested_query _
    # => {"a"=>"a", "b"=>[{"c"=>"c", "d"=>"d", "e"=>"e", "f"=>"f"}]}
    

提交回复
热议问题