Rails 4.2 如何在不同命名空间中遵循 DRY 原则? [英] How to follow DRY principles in different namespaces Rails 4.2?

查看:55
本文介绍了Rails 4.2 如何在不同命名空间中遵循 DRY 原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我开发了一个应用程序,它有两个命名空间:adminapi 和公共命名空间(例如简单的 resources :users).一切正常,但是我重复了很多,例如 api 中的一些控制器可以很容易地在 admin 中使用.

Basically I've developed an app which has two namespaces: admin, api and the public one (simply resources :users for instance). All works fine, however I'm repeating myself quite a bit as some of the controllers in api for instance could easily be used in admin.

在这种情况下,我怎样才能保持命名空间的 DRY 我的代码?

How can I DRY my code in this case keeping the namespaces?

谢谢!

推荐答案

我可以想到以下几种方法:

There are a couple ways I can think of doing it:

  1. (不推荐) - 将 url 发送到 routes.rb 文件中的同一个控制器.

  1. (NOT RECOMMENDED) - Send the urls to the same controller in your routes.rb file.

控制器继承的共享命名空间

例如你可以:

# controllers/shared/users_controller.rb
class Shared::UsersController < ApplicationController
  def index
    @users = User.all
  end
end


# controllers/api/users_controller.rb
class Api::UsersController < Shared::UsersController
end


# controllers/admin/users_controller.rb
class Admin::UsersController < Shared::UsersController
end 

以上将允许您在相关控制器之间共享您的索引操作.在这种情况下,您的路由文件将如下所示:

The above would allow you to share your index action across the relevant controllers. Your routes file in this case would look like this:

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

共享一个操作肯定需要很多代码,但价值会随着共享操作的数量成倍增加,而且最重要的是,您的代码位于一处.

That's definitely a lot of code to share one action, but the value multiplies as the number of shared actions does, and, most importantly, your code is located in one spot.

这篇关于Rails 4.2 如何在不同命名空间中遵循 DRY 原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆