routes

  • 重构路由

    有些项目是api和页面共存的. 大量充斥着重复的代码.

# 重构前
namespace :a do
  resources :users
  resources :orders
end

namespace :b do
  resources :users
  resources :orders
end

# 重构后
concern :base do
  resources :users
  resources :orders
end

namespace :a do
  concerns :base
end

namespace :b do
  concerns :base
end

来看看D大神的说法

  • 拆分重构

  • routes的内容移到其他文件里.

  • 首先创建一个实例.

    # vim config/initializers/routing_draw.rb
    # Adds draw method into Rails routing
    # It allows us to keep routing splitted into files
    class ActionDispatch::Routing::Mapper
    def draw(routes_name)
     instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))
    end
    end
  • routes文件里使用

Rails.application.routes.draw do
  draw :admin
end
  1. 创建对应的文件

    ps: 方便管理,在配置文件下创建一个路由文件夹.

#vim config/routes/admin.rb
namespace :admin do
  resources :users
end

Last updated