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.
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"}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With