我有五个共享通用代码的 Controller 。最好让它们从父 Controller 继承,还是使用关注点?例如:
class PostsController < ApplicationController
before_action :authenticate, :set_project
layout 'projects'
end
class CommentsController < ApplicationController
before_action :authenticate, :set_project
layout 'projects'
end
# three other controllers, etc...
我可以让 Controller 继承自一个声明了 before_actions
和 layout
的 Controller ,或者我可以将通用代码塞入一个关注点。
选择一个或另一个的标准是什么?有定义吗?
最佳答案
我的经验法则是:
如果 Controller 在 URL 中共享相同的命名空间(例如 /projects/...
或 /admin/...
),那么我使用继承自Projects::BaseController
或 Admin::BaseController
。
如果他们只是共享方法或声明而不共享命名空间,那么我会使用 mixins。
有时我更喜欢重复的代码。因为就地代码比名称无意义的混入更容易理解。对于涵盖身份验证
和布局
的问题,您是否有一个好名字?
关于ruby-on-rails - 从父 Controller 继承还是使用问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19230020/