Episodes

Routing Partials

Episode #80 by Teacher's Avatar David Kimura

Summary

The routes file can grow to be unmaintainable and messy. Learn to keep things organized by extracting out blocks of routes into their own files.
rails routes 4:30

Resources


Side Note: everyone should use caution in using instance_eval and be careful to not accept user inputs (or ensure they are sanitized). I feel that it is an acceptable use case here since only the code in the routes will call this method and it is not exposed.

Summary

# config/initializers/routing_draw.rb
class ActionDispatch::Routing::Mapper
  def draw(routes_name, sub_path=nil)
    if sub_path.present?
      instance_eval(File.read(Rails.root.join("config/routes/#{sub_path}/#{routes_name}.rb")))
    else
      instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))
    end
  end
end

# routes.rb
Rails.application.routes.draw do
  draw :api
  resources :users
  root to: 'users#index'
end

# config/routes/api.rb
require 'api_constraints'

namespace :api, compress: false do
  [:v1, :v2].map { |api| draw api, :api }
end

# config/routes/api/v1.rb
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: false) do
  resources :users
end