Ruby: How to turn a hash into HTTP parameters?

后端 未结 14 1615
故里飘歌
故里飘歌 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:50

    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.

    module QueryParams
    
      def self.encode(value, key = nil)
        case value
        when Hash  then value.map { |k,v| encode(v, append_key(key,k)) }.join('&')
        when Array then value.map { |v| encode(v, "#{key}[]") }.join('&')
        when nil   then ''
        else            
          "#{key}=#{CGI.escape(value.to_s)}" 
        end
      end
    
      private
    
      def self.append_key(root_key, key)
        root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
      end
    end
    

    Rolled up as gem here: https://github.com/simen/queryparams

提交回复
热议问题