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/.