How to get ALL of the URL parameters in a Sinatra app

Viewed 28128

Using the following Sinatra app

get '/app' do
  content_type :json
  {"params" => params}.to_json
end

Invoking:

/app?param1=one&param2=two&param2=alt

Gives the following result:

{"params":{"param1":"one","param2":"alt"}}

Params has only two keys, param1 & param2.

I understand Sinatra is setting params as a hash, but it does not represent all of the URL request.

Is there a way in Sinatra to get a list of all URL parameters sent in the request?

4 Answers

I believe by default params of the same name will be overwritten by the param that was processed last.

You could either setup params2 as an array of sorts

...&param2[]=two&param2[]=alt

Or parse the query string vs the Sinatra provided params hash.

kwon suggests to parse the query string. You can use CGI to parse it as follows:

require 'cgi'

get '/app' do
  content_type :json
  {"params" => CGI::parse(request.query_string)}.to_json
end

Invoking:

/app?param1=one&param2=two&param2=alt

Gives the following result:

{"params":{"param1":["one"],"param2":["two","alt"]}}

Related