Reputation: 2777
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.
Upvotes: 12
Views: 2355
Reputation: 2777
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
Upvotes: 11