-1

I want to load the instance method of create from the reqs string(routing term) and then find its source location This is how you would define it in the routes file

get "route_name" => "controller#action"

Typically, you can do this by using the following statement

UsersController.instance_method(:create).source_location or even "UsersController".constantize.instance_method(:create)

I was wondering if there is an easy way to do this. I know I can expand the slashes and split on the hash to load the instance method, but I am sure there's a quick way given that this is such a common thing in Rails routing

SoWhat
  • 5,564
  • 2
  • 28
  • 59

2 Answers2

0

Would this work (You would change find_path to whatever path you want to find)?

find_path = '/'
controller_name = Rails.application.routes.recognize_path(find_path)[:controller]
controller_class = (controller_name + '_controller').classify.constantize
controller_class.instance_method(:create).source_location

I don't know if you prefer to parse the routes.rb file. If not, you can get a list of all your application's routes with the following method: Method: ActionDispatch::Routing::RouteSet#named_routes

Let me know if I'm misunderstanding.

Will Mavis
  • 393
  • 3
  • 8
  • So I did all of this earlier. I used the RouteInspector to get the routes and received the reqs argument. I was wondering if there is a way to directly parse the string in ruby. I ended up doing this `execution_path = 'api/vi1/users_controller#create' controller,action = execution_path.split("#") controller = controller + "_controller" controller_class = controller.camelize.constantize source_code = controller_class.instance_method(action).source` – SoWhat Jul 15 '18 at 04:48
0

So I ended up using the following code:

execution_path= "api/v1/users_controller#action"
controller,action = execution_path.split("#")
controller = controller + "_controller"
controller_class = controller.camelize.constantize
source_code = controller_class.instance_method(action).source_location
SoWhat
  • 5,564
  • 2
  • 28
  • 59