我知道我可以使用request.referrer
在Rails中获取完整的引用URL,但有没有办法从URL获取控制器名称?
我想看看http://myurl.com/profiles/2的网址是否包含“个人资料”
我知道我可以使用正则表达式来做,但我想知道是否有更好的方法。
在控制器内部,你有方法controller_name
,它只返回你的名字。在您的情况下,它将返回“配置文件”。您也可以使用返回相同字符串的params[:controller]
。
请记住,request.referrer
会在当前请求之前为您提供请求的网址。也就是说,以下是如何将request.referrer
转换为controller / actionn信息:
Rails.application.routes.recognize_path(request.referrer)
它应该给你一些类似的东西
{:controller => "x", :action => "y"}
这是我的尝试,它适用于Rails 3和4.此代码在注销时提取一个参数,并将用户重定向到自定义登录页面,否则重定向到常规登录页面。你可以这样轻松地提取:controller
。控制器部分:
def logout
auth_logout_user
path = login_path
begin
refroute = Rails.application.routes.recognize_path(request.referer)
path = subscriber_path(refroute[:sub_id]) if refroute && refroute[:sub_id]
rescue ActionController::RoutingError
#ignore
end
redirect_to path
end
测试也很重要:
test "logout to subscriber entry page" do
session[:uid] = users(:user1).id
@request.env['HTTP_REFERER'] = "http://host/s/client1/p/xyzabc"
get :logout
assert_redirected_to subscriber_path('client1')
end
test "logout other referer" do
session[:uid] = users(:user1).id
@request.env['HTTP_REFERER'] = "http://anyhost/path/other"
get :logout
assert_redirected_to login_path
end
test "logout with bad referer" do
session[:uid] = users(:user1).id
@request.env['HTTP_REFERER'] = "badhost/path/other"
get :logout
assert_redirected_to login_path
end