Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you determine if request.referrer matches a Rails restful path?

As we know from this post, in Rails, you can get the previous url by calling

request.referrer

But how do you check if the previous url matches one of the restful paths in your Rails application?

By restful paths, I mean paths provided by Rails, such as,

books_path
book_path(book)
edit_book_path(book)

Of course I can do a regular expression string match on request.referrer, but I think it's a bit ugly.

One particular case, in my application, is that request.referrer can be "localhost:3000/books?page=4"

and I want to it to match

books_path

which returns "/books"

In this case, how can I check if there's a match without doing regular expression string match? (if this is at all possible)

Thanks

P.S. I have tried regular expression string match, and it works. I just thought there might be a better way in Rails.

like image 453
Zack Xu Avatar asked Aug 29 '13 16:08

Zack Xu


2 Answers

You could extract the path portion of the request.referer using the following:

URI(request.referer).path

You can then use Rails.application.routes.recognize_path to check if path maps to a controller and action, e.g.:

my_path = URI(request.referer).path 
# => /books

Rails.application.routes.recognize_path(my_path)
# => {:action=>"show", :controller=>"books", :page=>"4"}
like image 173
vee Avatar answered Oct 07 '22 01:10

vee


Since recognize_path was deprecated, this is another way of doing it:

Name your route in your routes config using the as keyword:

get 'foo/bar' => 'foo#bar', as: :foo_bar

Then you can do the check like this:

if URI(request.referer).path == foo_bar_path
  do_something()
end
like image 26
fgblomqvist Avatar answered Oct 07 '22 02:10

fgblomqvist