1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def array_to_params(param_name, params) unless params.is_a?(Array) result = "&#{param_name}[0]=#{params}" else result = "" for i in 0 .. params.length-1 do result += "&#{param_name}[i]=#{params[i]}" end end result end http = Net::HTTP.new(uri.host, uri.port) response = http.post(path, "user=test_user" + array_to_params)
Refactorings
No refactoring yet !
sfusion
June 1, 2010, June 01, 2010 12:04, permalink
would you not be better providing the input as a hash?
1 2 3 4 5
params = { :param_one => 'foo', :param_two => 'bar' } def hash_to_params hsh hsh.map { |k, v| "#{k}=#{v}" }.join '&' end
Martin Plöger
June 1, 2010, June 01, 2010 14:58, permalink
Rails has a Hash#to_param-method
1
{ :param_one => 'foo', :param_two => 'bar' }.to_param
arvanasse
June 1, 2010, June 01, 2010 15:03, permalink
This refactoring does not provide the leading '&' for the query. You can decide whether that's better to prepend to the last line of the method or append in the line that calls it.
1 2 3 4 5 6 7 8 9 10 11 12
def array_to_params(param_name, params) # normalize to an array first params = [params] unless params.is_a?(Array) param_list = [ ] params.each_with_index{|item, idx| param_list.push "#{param_name}[#{idx}]=#{item}" } param_list.join('&') end http = Net::HTTP.new(uri.host, uri.port) response = http.post(path, "user=test_user" + array_to_params)
zealer.livejournal.com
June 3, 2010, June 03, 2010 08:25, permalink
Finally I choose arvanasse variant but without creating array.
I think, it isn't necessary
1 2 3 4 5 6 7 8 9 10 11 12
def array_to_params(param_name, params) # normalize to an array first params = [params] unless params.is_a?(Array) param_string = "" params.each_with_index{|item, idx| params << "&#{param_name}[#{idx}]=#{item}" } param_string end http = Net::HTTP.new(uri.host, uri.port) response = http.post(path, "user=test_user" + array_to_params)
I need to post some array using ruby.
It should be like: &data[0]=blahblah1&data[1]=blahblah2
UPD:
I have requirement for POST parameters. I can not change parameters names.
In fact, I have to post on several pages.
On first page I need to post with parameters named "data" (data[0]... data[n]).
On second page I need to post with parameters named "ids" (ids[0]... ids[n]).
and so on.