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.
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 (.
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.
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.
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.
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
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