rails 3 - code shared between multiple controllers - where to put it?

会有一股神秘感。 提交于 2019-12-21 09:15:17

问题


I have a piece of code that is needed in 2 of my controllers, but not all of them. Where does this method belong? I have read about helpers, but those seem to be for view-related code. Someone proposed the lib-folder, but that seems 'too far away' from the controller logic, i don't need it in views or models. Has someone experience with that sort of problem?


回答1:


There are three options, the easiest (though, the most unclean) is the application controller. The other two options are a shared parent controller

class FooController < FooBarParentController
   # code here  
end

class BarController < FooBarParentController
   # code here  
end

Usage depends on how related these controllers are.

The final solution is a module

module FooBarModule
  extend ActiveSupport::Concern

  included do
    # class level code
    # before_filter ....
  end

  module ClassMethods
    # all class methods here
  end

  # instance methods here
end

This is where the shared code required is for a handful of ad-hoc controllers, or if you are already using the inheritance above and this code doesn't quite fit into this subset (thus attempting to emulate multiple inheritance).



来源:https://stackoverflow.com/questions/7056599/rails-3-code-shared-between-multiple-controllers-where-to-put-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!