2013-02-02 73 views
22

我知道我可以使用request.referrer在Rails中获取完整的请求URL,但有没有办法从请求中获取控制器名称?从Rails中的request.referer获取控制器名称的好方法

我想看看的http://myurl.com/profiles/2的URL包括“曲线”

我知道我可以使用正则表达式来做到这一点,但我想知道是否有更好的方法。

+0

它似乎并没有成为一个正确的做法都没有。如果其他服务器是引用者呢? – Eru

+1

http:// localhost:3000 好的测试完成感谢球员:) –

+0

请@ tvalent2,重新选择正确的答案。赞助人自己说话。 –

回答

-2

在控制器内部,您有方法controller_name,它只返回名称。在你的情况下,它会返回“配置文件”。 您也可以使用返回相同字符串的params[:controller]

+15

这个问题不正确地被接受吗?他不想知道如何分解引用者的动作/控制器而不是当前动作? – GigaBass

82

请记住,request.referrer为您提供当前请求的URL。这就是说,这里是你如何可以转换request.referrer到控制器/ actionn信息:

Rails.application.routes.recognize_path(request.referrer) 

它应该给你类似

{:controller => "x", :action => "y"} 
+1

天才。谢谢。 – Abram

+4

'Rails.application.routes.recognize_path(request.referrer)[:controller]'是精确的。 – marcantonio

+2

非常感谢,先生,你节省了我的时间。 –

4

这是我尝试它使用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 
+0

TDD上的一个答案! –

相关问题