Search route path from url string

I want to know what the api request route is.

Let's say, for example, api_v1_user_session _path is the route for /api/v1/users/sign_in url

If the request comes from /api/v1/users/sign_in How to find out what the route is. In this case, it should be api_v1_user_session _path

I tried the instructions below, but it gives the controller and action, but does not route.

 Rails.application.routes.recognize_path('/api/v1/users/sign_in') => {:controller=>"api/v1/sessions", :action=>"new"} 

Is there any method like this

 Rails.application.routes.get_route('/api/v1/users/sign_in') => api_v1_user_session 

How can I get this route from a URL or from a request object.

+6
source share
1 answer

With a great search, I was able to figure it out myself.

 class StringToRoute attr_reader :request, :url, :verb def initialize(request) @request = request @url = request.original_fullpath @verb = request.request_method.downcase end def routes Rails.application.routes.routes.to_a end def recognize_path Rails.application.routes.recognize_path(url, method: get_verb) end def process _recognize_path = recognize_path routes.select do |hash| if hash.defaults == _recognize_path hash end end end def get_verb verb.to_sym end def path "#{verb}_#{process.name}" end end 

Result:

StringToRoute.new(request).path

+4
source

All Articles