解码重定向网址 - Ruby on Rails

时间:2015-07-09 16:58:49

标签: ruby-on-rails ruby ruby-on-rails-3 url

我想使用URI或CGI库来获取此url的查询部分的路径。换句话说,只是:'/ scouting / amateur'。这是可能的还是我需要使用正则表达式?

http://10.241.180.63:3149/login?redirect_path=http%3A%2F%2F10.241.180.63%3A3149%2Fscouting%2Famateur

2 个答案:

答案 0 :(得分:1)

使用Ruby内置函数建议(如果设计方法,您可能希望实现一些错误处理)。

require 'uri'

query = URI("http://10.241.180.63:3149/login?redirect_path=http%3A%2F%2F10.241.180.63%3A3149%2Fscouting%2Famateur").query

path = URI(URI.decode(query).split('=')[1]).path

您可能会发现gem uri-query_params有用/更优雅(它会自动解码查询参数)。 E.g。

require 'uri/query_params'

uri = URI("http://10.241.180.63:3149/login?redirect_path=http%3A%2F%2F10.241.180.63%3A3149%2Fscouting%2Famateur")

URI(uri.query_params["redirect_path"]).path

答案 1 :(得分:0)

试试这个 -

url = URI.parse('http:://10.241.180.63:3149/login?redirect_path=http%3A%2F%2F10.241.180.63%3A3149%2Fscouting%2Famateur')

redirect_path = u.opaque.split("redirect_path=").last
# redirect_path is now {"redirect_path"=>["http://10.241.180.63:3149/scouting/amateur"]}

result = redirect_path.split("/").last(2).join("/")
# result = 'scouting/amateur'