167c4580d7b338553023cc575ecc2af7

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.

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 !

4f5d54213efb6502baab202f3fb2f09e

sfusion

June 1, 2010, June 01, 2010 12:04, permalink

1 rating. Login to rate!

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
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

June 1, 2010, June 01, 2010 14:58, permalink

1 rating. Login to rate!

Rails has a Hash#to_param-method

1
{ :param_one => 'foo', :param_two => 'bar' }.to_param
7855792dbc5f3b4c365344314e2b1ad6

arvanasse

June 1, 2010, June 01, 2010 15:03, permalink

2 ratings. Login to rate!

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)
167c4580d7b338553023cc575ecc2af7

zealer.livejournal.com

June 3, 2010, June 03, 2010 08:25, permalink

No rating. Login to rate!

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)

Your refactoring





Format Copy from initial code

or Cancel