Inverse route matching

The phoenix routers define functions like controller_name_path to convert routes into strings. Is there a way of getting this match given the controller module and the function name? Something like:

MyApp.Router.route_for(MyController, :my_function)

You could do:

Enum.filter(MyApp.Router.__routes__, fn route ->
    route.plug == MyApp.MyController && route.opts == :my_function

fyi __routes__ is not a public API so don’t depend on it not changing out from under you. What’s the goal with the inverse route match? From your provided example, it’s possible you’d have multiple routes given a controller/action, but what what’s your end goal with this ability?

1 Like

My goal was to generate some controlers and routes automatically, and be able to link to them from templates. But It’s probably not the way to go, especially if there isn’t a ready to use API for it. Thanks.

I don’t think you need any new feature for that. You can generate some routes on the router and use the router helpers that phoenix generates within the templates. For example, what else is needed if you can do;

# router

for {path, controller} <- [{"foo", FooController}, {"bar", BarController}, ...] do
  get path, controller, :index

# then later in a template
# <%= link "whatevs", to: foo_path(@conn, :index) %>

Thanks, this is indeed enough for my use case.