Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding routes path from url string

I want to know what is the route of api request.

Lets say for example api_v1_user_session_path is the route for /api/v1/users/sign_in url

If a request is coming from /api/v1/users/sign_in How can I find out what is the route. In this scenario it should be api_v1_user_session_path

I tried below statement but it is giving controller and action but 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 url or from request object.

like image 797
Ashwin Yaprala Avatar asked Oct 21 '15 19:10

Ashwin Yaprala


People also ask

How do I find the path of a URL?

The path refers to the exact location of a page, post, file, or other asset. It is often analogous to the underlying file structure of the website. The path resides after the hostname and is separated by “/” (forward slash). The path/file also consists of any asset file extension, such as images (.

How do I find routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What is match in Rails routes?

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

What is namespace in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.


1 Answers

With more search I was able to figure it 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

like image 146
Ashwin Yaprala Avatar answered Oct 03 '22 07:10

Ashwin Yaprala