Arrays in params

10 views
Skip to first unread message

candlerb

unread,
Feb 8, 2009, 5:50:27 AM2/8/09
to sinatrarb
I'm not sure if the following is intentional behaviour, or if not,
whether the problem lies in Sinatra or Rack.

You can name your form parameters 'foo[]' to build an array. However,
if there is exactly one parameter with this name, then you *don't* get
an array, but rather just a string. Example:

----------------
require 'rubygems'
require 'sinatra'

post '/' do
params.inspect + "\n"
end
----------------

$ curl -d 'post[foo][]=bar&post[foo][]=baz' http://localhost:4567/
{"post"=>{"foo"=>["bar", "baz"]}}
$ curl -d 'post[foo][]=bar' http://localhost:4567/
{"post"=>{"foo"=>"bar"}}

In the second case I was expecting to see
{"post"=>{"foo"=>["bar"]}}

This complicates controller code, as there are three cases to
consider:

- nil (nothing provided)
- string (one element provided)
- array (more than one element provided)

But Rails behaves how I expected:

----------------
class FooController < ApplicationController
def bar
render :text => params.inspect+"\n"
end
end
----------------

$ curl -d 'post[foo][]=bar' http://localhost:3000/foo/bar
{"post"=>{"foo"=>["bar"]}, "action"=>"bar", "controller"=>"foo"}

[Need "config.action_controller.allow_forgery_protection = false"
for this to work with curl]

Regards,

Brian.

Ryan Tomayko

unread,
Feb 8, 2009, 9:30:47 AM2/8/09
to sina...@googlegroups.com
On Sun, Feb 8, 2009 at 2:50 AM, candlerb <b.ca...@pobox.com> wrote:
>
> I'm not sure if the following is intentional behaviour, or if not,
> whether the problem lies in Sinatra or Rack.
>
> You can name your form parameters 'foo[]' to build an array. However,
> if there is exactly one parameter with this name, then you *don't* get
> an array, but rather just a string. Example:

Sinatra's nested params implementation does not currently support the
Array syntax. Multiple same named parameters result in an Array being
created. A more thorough nested params implementation with support for
the Array syntax landed in Rack recently. We'll be ripping Sinatra's
current implementation out and using Rack's as soon as a Rack release
is available.

I'm surprised the current implementation is giving even semi-sane
results, actually. If you can come up with a small (+ 1-2 line) patch
that adds proper support for Arrays, I'd be happy to merge it.

candlerb

unread,
Feb 8, 2009, 11:17:47 AM2/8/09
to sinatrarb
> Sinatra's nested params implementation does not currently support the
> Array syntax. Multiple same named parameters result in an Array being
> created. A more thorough nested params implementation with support for
> the Array syntax landed in Rack recently. We'll be ripping Sinatra's
> current implementation out and using Rack's as soon as a Rack release
> is available.

That's good news... I can wait for that.

Cheers,

Brian.
Reply all
Reply to author
Forward
0 new messages