Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra and question mark

I need to make some methods with Sinatra that should look like:

http//:localhost:1234/add?string_to_add

But when I declare it like this:

get "/add?:string_to_add" do
...
end

it doesn't see the string_to_add param.

How should I declare my method and use this parameter to make things work?

like image 592
earsonheart Avatar asked Apr 02 '13 20:04

earsonheart


1 Answers

In a URL, a question mark separates the path part from the query part. The query part normally consists of name/value pairs, and is often constructed by a web browser to match the data a user has entered into a form. For example a url might look like:

http://example.com/submit?name=John&age=93

Here the path section in /submit, and the query sections is name=John&age=93 which refers to the value “John” for the name key, and “93” for the age.

When you create a route in Sinatra, you only specify the path part. Sinatra then parses the query, and makes the data in it available in the params object. In this example you could do something like this:

get '/submit' do
  name = params[:name]
  age = params[:age]
  # use name and age variables
  ...
end

If you use a ? character when defining a Sinatra route, it makes part of the url optional. In the example you used (get "/add?:string_to_add"), it will actually match any url starting with /ad, then optionally another d, and then anything else will be put in the :string_to_add key of the params hash, and the query section will be parsed separately. In other words the question mark makes the preceding d character optional.

If you want to get the ‘raw’ text of the query string in Sinatra, you can use the query_string method of the request object. In your example that would look something like this:

get '/add' do
  string_to_add = request.query_string
  ...
end

Note that the route doesn’t include the ? character, just the base /add.

like image 104
matt Avatar answered Oct 24 '22 07:10

matt