我一直在开发一个 CMS 应用程序来提高我的技能,而 Controller 的定义变得非常臃肿。我知道可以将内容存储在 lib/whatever.rb 中,然后使用 require 和 include,但这对 Controller 不太有效——至少,在我的例子中,我有 before_filters。 如果 Controller 中没有正确的定义,before_filters 将无法工作。
是否所有的 defs 都必须放入 Controller 中,还是有办法将它们取出? (它们特定于该 Controller ,因此不能进入应用程序 Controller 。
最佳答案
您可以使用 mixin 模块做很多事情,这些模块将向现有 Controller 添加行为,或者您可以尝试提出一个类层次结构,允许 Controller 从其父类继承所需的方法。
在大多数应用程序中,我至少将 ApplicationController
子类化一次,以便在某些上下文中强制执行某些标准。例如,与项目相关的所有 Controller 都将继承自 ProjectController::Base
:
class ProjectController::Base < ApplicationController
before_filter :must_be_logged_in
before_filter :load_project
protected
def load_project
@project = Project.find(params[:project_id] || params[:id])
rescue ActiveRecord::RecordNotFound
render(:template => 'not_found')
end
def must_be_logged_in
# ...
end
end
关于ruby-on-rails - Rails 3 - 如何组织/拆分臃肿的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6271087/