Sinatra和问号 [英] Sinatra and question mark

查看:100
本文介绍了Sinatra和问号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


http //:localhost:1234 / add?string_to_add


但是当我声明如下:

  get/ add?:string_to_adddo 
...
end

它没有看到 string_to_add param。



如何声明我的方法并使用它参数使事情工作?

解决方案

在URL中,问号将路径部分来自查询部分。查询部分通常由名称/值对组成,并且通常由Web浏览器构建以匹配用户输入到表单中的数据。例如,url可能如下所示:

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

这里 / submit ,并且查询部分是 name = John& age = 93 ,它引用 name的值John code>键和<93 $> age



在Sinatra中创建路线,您只指定路径部分。 Sinatra然后解析查询,并使其中的数据在 params 对象中可用。在这个例子中,你可以做这样的事情:

  get'/ submit'do 
name = params [:name ]
age = params [:age]
#使用名称和年龄变量
...
end

如果在定义Sinatra路线时使用字符,则它会使url的一部分为可选项。在您使用的示例中( get/ add?:string_to_add),它实际上会匹配任何以 / ad ,然后可以选择另一个 d ,然后其他任何东西都会放入params散列的:string_to_add 键中,并且查询部分将被分别解析。换句话说,问号使前面的 d 字符是可选的。



如果你想获得'raw'查询字符串在Sinatra中的文本,您可以使用 query_string 请求对象的方法。在你的例子中,它看起来像这样:

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

请注意,路由不包含字符,只是基础 / add


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?

解决方案

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.

这篇关于Sinatra和问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆