`
Hooopo
  • 浏览: 329358 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Nested HTTP params on ruby HTTP requests[via comp]

    博客分类:
  • Ruby
阅读更多
Hi,
I'm using ruby HTTP classes to send POST requests to a server. The
problem is that I'm posting some many-levels hierarchical structures on
my form . When POST parameters are simple key/value there's no
serialization problem with form_data method on PostRequest.
{ :a => :b} => "a=b" 

When the values are arrays it works fine too
{ :a => [:b,:c,:d]} => "a[]=b&a[]=c&a[]=d" 

But when values are hashes serialization doesn't work as expected.
For example
{ :a => [{:b => :c}, {:d => :e}]} => "a[][b]=c&a[][d]=e" 

I don't know if there's any other way to do it but browsing the code it
seems that only one nesting level is supported (maybe is an issue on my
ruby version 1.8.6).
I developed a tiny serialization method. Is a quick and dirty code (the
first release I've made) but it works for me.
module FormSerializer 
  require "erb" 
  include ERB::Util 
  def serialize_form_data(data, path = "",serialized_params = []) 
    if data.kind_of? Hash 
      data.each_pair{|k,v| token = (path == "" ? url_encode(k) : 
"[#{url_encode(k)}]"); serialize_form_data(v, "#{path}#{token}", 
serialized_params)} 
    elsif data.kind_of? Array 
       data.each{|v| serialize_form_data(v, "#{path}[]", 
serialized_params) } 
    else 
      #end of recursion 
      serialized_params << "#{path}=#{url_encode(data)}" 
    end 
    return serialized_params.join("&") if (path == "") 
  end 
  #{ :a => :b} = "a=b" 
  #{ :a => [:b,:c,:d]} = "a[]=b&a[]=c&a[]=d" 
  #{ :a => :b, :b => :c} = "a=b&b=c" 
  #{ :a => {:b => :c}} = "a[b] = c" 
  #{ :a => [{:b => :c}, {:d => :e}]} = "a[][b] = c & a[][d] = e" 
end 

After this I only needed to modify
     
def form_data(params, sep = '&') 
          self.body = serialize_form_data(params) 
          self.content_type = 'application/x-www-form-urlencoded' 
      end 

I just finished the code some hours ago, basic testing has been
performed.
Hope this will be useful for anyone!
Best regards
Dave Garcia
--
Posted via http://www.ruby-forum.com/.


PS:
On the server side Rails 2.3.2 works fine deserializing my params are :
{"a"=>[{"b"=>"c", "d"=>"e"}], "action"=>"show", 
"controller"=>"identities"} 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics