Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting controller name from a request.referer in Rails

I know I can use request.referrer to get the full referrer URL in Rails, but is there a way to just get the controller name from the URL?

I want to see if the URL of http://myurl.com/profiles/2 includes "profiles"

I know I can use a regex to do it but I wondered if there was a better way.

like image 781
tvalent2 Avatar asked Feb 02 '13 15:02

tvalent2


2 Answers

Keep in mind that request.referrer gives you the url of the request before the current one. That said, here is how you can convert request.referrer to controller/actionn information:

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

it should give you something like

{:subdomain => "", :controller => "x", :action => "y"} 
like image 144
moritz Avatar answered Sep 19 '22 19:09

moritz


Here is my try which works with Rails 3 & 4. This code extracts one parameter on logout and redirects user to customized login page otherwise it redirects to general login page. You can easily extract :controller this way. Controller part:

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 

And tests are important as well:

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 
like image 21
gertas Avatar answered Sep 17 '22 19:09

gertas