TIL you can list Rails routes programmatically

Oliver Peate posted on June 17th, 2019

You can find each route in a Rails app via Rails.application.routes.routes (an array of ActionDispatch::Journey::Route). Each route has a path which has a spec like:

/admin/users(.:format)
/admin/users(.:format)
/admin/users/new(.:format)
/admin/users/:id/edit(.:format)
/admin/users/:id(.:format)

If we want to use these routes in an automated test for example, we can build URLs with the placeholders replaced (:id) and determine the HTTP method to use:

Route = Struct.new(:path, :http_method) do
  def to_s
    "#{http_method} #{path}"
  end
end

routes = Rails.application.routes.routes.map do |route|
  built_path = route.path.build_formatter.evaluate({ id: 123 })
  Route.new(built_path, route.verb)
end

A sample of the hydrated routes:

routes.select do |route|
  if route.path.start_with?("/admin/users")
    puts route
  end
end

# GET /admin/users
# POST /admin/users
# GET /admin/users/new
# GET /admin/users/123/edit
# GET /admin/users/123
# PATCH /admin/users/123
# PUT /admin/users/123
# DELETE /admin/users/123

What did you learn today?

Write a quick TIL post to reflect on what you've learned.

Write a post