如何遵循DRY原则在不同的命名空间的Rails 4.2? [英] How to follow DRY principles in different namespaces Rails 4.2?
问题描述
基本上,我已经开发出了拥有两个命名空间的应用程序:管理
, API
和公众一(简单资源:用户
的实例)。一切工作正常,但是我重复自己颇有几分一些控制器在 API
比如可以很容易地在使用管理
。
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
.
我怎样才能干我的code在这种情况下保持命名空间?
How can I DRY my code in this case keeping the namespaces?
谢谢!
推荐答案
有几种方法我能想到这样做的:
There are a couple ways I can think of doing it:
-
(不推荐) - 发送的URL相同的控制器在你的routes.rb文件
(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
这绝对是一个很大code可以共享一个动作,但价值的乘法,如共同行动的数量呢,而且,最重要的是,你的code位于一个地方。
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.
这篇关于如何遵循DRY原则在不同的命名空间的Rails 4.2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!