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?
You should declare it as:
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:
Here the path section in
/submit
, and the query sections isname=John&age=93
which refers to the value “John” for thename
key, and “93” for theage
.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: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 anotherd
, 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 precedingd
character optional.If you want to get the ‘raw’ text of the query string in Sinatra, you can use the
query_string
method of therequest
object. In your example that would look something like this:Note that the route doesn’t include the
?
character, just the base/add
.