rails 3-多个控制器之间共享的代码-放在哪里? [英] rails 3 - code shared between multiple controllers - where to put it?

查看:39
本文介绍了rails 3-多个控制器之间共享的代码-放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器中需要的一段代码,但不是全部.这种方法在哪里? 我已经阅读了有关助手的文章,但是这些似乎是针对视图相关代码的.有人提出了lib文件夹,但是这似乎与控制器逻辑相距太远",我在视图或模型中不需要它. 有人遇到过这种问题吗?

解决方案

共有三个选项,最简单(尽管最不干净)的是应用程序控制器.其他两个选项是共享的父控制器

class FooController < FooBarParentController
   # code here  
end

class BarController < FooBarParentController
   # code here  
end

使用情况取决于这些控制器之间的关联程度.

最终的解决方案是一个模块

module FooBarModule
  extend ActiveSupport::Concern

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

  module ClassMethods
    # all class methods here
  end

  # instance methods here
end

这是少数几个临时控制器所需的共享代码的地方,或者如果您已经在使用上面的继承,并且此代码不太适合该子集(因此尝试模拟多个继承). /p>

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?

解决方案

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).

这篇关于rails 3-多个控制器之间共享的代码-放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆