[英]Rails 3 - how to organize / split up bloated controllers?
I've been working on a CMS app to sharpen up my skills and the controllers are getting quite bloated with the definitions.我一直在开发一个 CMS 应用程序来提高我的技能,而控制器的定义变得相当臃肿。 I know it's possible to store stuff in lib/whatever.rb and then use require and include, but that doesn't quite work with controllers - at least, in my case, where I have before_filters.我知道可以将内容存储在 lib/whatever.rb 中,然后使用 require 和 include,但这不适用于控制器 - 至少在我的情况下,我有 before_filters。 Without the definitions right in the controller, before_filters refuse to work.如果没有 controller 中的正确定义, before_filters 将拒绝工作。
Do all the defs HAVE to go in the controller or is there a way to take them out? controller 中的所有 defs 是否都包含到 go 或者有没有办法将它们取出? (They are specific to that controller so they can't go in application controller. (它们特定于 controller,因此它们不能在应用程序 controller 中使用 go。
You can do a lot of things with mixin modules that will add behavior to an existing controller, or you can try and come up with a class hierarchy that will allow the controllers to inherit the required methods from their parent class.您可以使用 mixin 模块做很多事情,将行为添加到现有的 controller,或者您可以尝试提出一个 class 层次结构,该层次结构将允许控制器从其父 ZA2F2ED4F8EBC2CBB4C21A29DZ4 继承所需的方法。
In most applications I sub-class ApplicationController
at least once in order to enforce some standards in certain contexts.在大多数应用程序中,我至少将ApplicationController
子类化一次,以便在某些上下文中强制执行某些标准。 For instance, all controllers relating to a Project would inherit from ProjectController::Base
:例如,与项目相关的所有控制器都将继承自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
The augmentation-plugin (it's rather a snippet) could be a solution for you.增强插件(它是一个片段)可能是您的解决方案。
class ::Object
def self.augment(*mods)
include *mods
mods.each {|mod| class_eval &mod.augmentation }
end
end
class ::Module
def augmentation(&block)
@augmentation ||= block
end
end
# app/controllers/your_controller.rb
class YourController
augment YourController::Stuff
...
end
# app/controllers/your_controller/stuff.rb
module YourController::Stuff
augmentation do
before_filter :something
def something
...
end
end
end
You need to make sure that subfolders of folders in /app
are included in Rails' autoload paths.您需要确保/app
中文件夹的子文件夹包含在 Rails 的自动加载路径中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.