如何在路线中使用Sinatra URL作为参数?

时间:2013-07-30 21:40:59

标签: ruby routes sinatra

我正在使用Sinatra路由,如果可能的话,我想解释一个普通的HTTP地址作为路由中的参数:

url http://somesite/blog/archives   

路线是:

/http://somesite/blog/archives 

代码是:

get '/:url' do |u|  
(some code dealing with url)

HTTP URL中的各种'/'会产生问题。

我找到的解决方法是仅传递上面示例中“somesite”所代表的URL部分,然后使用:

get '/:url' do |u|
buildUrl = "http://#{u}/blog/archives"
(some code dealing with url)

有没有办法直接处理完整的网址?

2 个答案:

答案 0 :(得分:6)

这不会像您指定的那样有效。正如您所注意到的那样,斜线会带来麻烦。你可以做的是将URL作为查询字符串参数传递而不是URL的一部分。

get '/example' do
  url = params[:url]
  # do code with url
end

然后,您可以通过将数据发送到http://yoursite.com/example?url=http://example.com/blog/archives

来抓取您想要的任何内容

答案 1 :(得分:0)

你想要的并不明显,但是,一般来说,Ruby的内置URI类对于剥离URL,修改它们然后重构它们非常有用。如果它不够复杂,Addressable::URI宝石应该填补任何遗漏的漏洞:

require 'uri'
param = '/http://somesite/blog/archives'
scheme, userinfo, host, port, registry, path, opaque, query, fragment = URI.split(param[1..-1])
=> ["http", nil, "somesite", nil, nil, "/blog/archives", nil, nil, nil]