Impetus
It would be nice to have --json
available for rails routes
so that it can be used for programmatic access. It would make parsing the existing routes output less error prone, which is great for tools like this vscode extension. I also think it would be beneficial to include the source location for the controller action as well, as that is also useful for extension development. Apart from extension development, I think it would also be useful for generating static docs based off of it. That is currently already possible without custom parsing of the existing format of course, but it’s a lot easier to just deserialize JSON.
Implementation
Here is a first-attempt at an implementation to add it.
If you spin up a brand new rails project and set your routes.rb
to:
Rails.application.routes.draw do
get "up", to: "rails/health#show", as: :rails_health_check
get "service-worker", to: "rails/pwa#service_worker", as: :pwa_service_worker
get "manifest", to: "rails/pwa#manifest", as: :pwa_manifest
namespace :admin do
resources :users
end
end
Then running bin/rails routes --json
will give you output that looks like this:
[
{
"prefix": "",
"verb": "",
"uri": "/assets",
"controller": {
"name": "Propshaft::Server",
"class": "Propshaft::Server",
"action": null,
"source_location": "/home/vscode/.rbenv/versions/3.3.4/lib/ruby/gems/3.3.0/gems/propshaft-0.9.0/lib/propshaft/server.rb:4"
},
"route_source_location": "propshaft (0.9.0) lib/propshaft/railtie.rb:42"
},
{
"prefix": "pwa_service_worker",
"verb": "GET",
"uri": "/service-worker(.:format)",
"controller": {
"name": "rails/pwa",
"class": "Rails::PwaController",
"action": "service_worker",
"source_location": "/workspaces/rails/railties/lib/rails/pwa_controller.rb:8"
},
"route_source_location": "/workspaces/rails/tmp/my-test-app/config/routes.rb:9"
},
{
"prefix": "admin_users",
"verb": "GET",
"uri": "/admin/users(.:format)",
"controller": {
"name": "admin/users",
"class": "Admin::UsersController",
"action": "index",
"source_location": null
},
"route_source_location": "/workspaces/rails/tmp/my-test-app/config/routes.rb:13"
},
...
]