プロジェクト自体が大きくなってきた際に routes.rb にまとめて記載すると見づらくて追加しようとした際にわかりずらい課題が発生した
そのため、rails で routes.rb を分割管理する方法を備忘録として残しておく
参考

環境

  • ruby: 3.0.5
  • rails: 6.1.7

方法

  • concern を使用して共通の routes を定義する
  • draw を使用して別ファイルに分割する

前提

config
 |-routes
 |  |-concerns.rb                # プロジェクト共通の routes
 |  |-foo_service_provider.rb    # Foo サービス用の routes
 |  |-hoge_service_provider.rb   # Hoge サービス用の routes
 |  |-service_provider_common.rb # サービス共通の routes
 |-routes.rb

実際の例

concern :loggable do
  get "login", to: "sessions#new"
  post "login", to: "sessions#create"
  delete "logout", to: "sessions#destroy"
end

concern :data do
  namespace :data do
    get "download"
  end
end
namespace :service_provider, path: "services" do
  concerns :loggable

  scope :home, as: :home do
    get "/", to: "home#index"
  end
end

draw(:service_provider_common)
namespace :service_provider, path: "services" do
  concerns :data
end

draw(:service_provider_common)
namespace :service_provider, path: "services" do
  resources :users, only: [:index, :show]
end
# == Route Map
#
#                              Prefix Verb   URI Pattern                            Controller#Action
#                         admin_login GET    /admin/login(.:format)                 admin/sessions#new
#                                     POST   /admin/login(.:format)                 admin/sessions#create
#                        admin_logout DELETE /admin/logout(.:format)                admin/sessions#destroy
#          foo_service_provider_login GET    /foo/services/login(.:format)          foo/service_provider/sessions#new
#                                     POST   /foo/services/login(.:format)          foo/service_provider/sessions#create
#         foo_service_provider_logout DELETE /foo/services/logout(.:format)         foo/service_provider/sessions#destroy
#           foo_service_provider_home GET    /foo/services/home(.:format)           foo/service_provider/home#index
#          foo_service_provider_users GET    /foo/services/users(.:format)          foo/service_provider/users#index
#           foo_service_provider_user GET    /foo/services/users/:id(.:format)      foo/service_provider/users#show
# hoge_service_provider_data_download GET    /hoge/services/data/download(.:format) hoge/service_provider/data#download
#         hoge_service_provider_users GET    /hoge/services/users(.:format)         hoge/service_provider/users#index
#          hoge_service_provider_user GET    /hoge/services/users/:id(.:format)     hoge/service_provider/users#show

Rails.application.routes.draw do
  draw(:concerns)

  namespace :admin do
    concerns :loggable
  end

  namespace :foo do
    draw(:foo_service_provider)
  end

  namespace :hoge do
    draw(:hoge_service_provider)
  end
end