【问题标题】:Where to locate methods used by multiple Rails controllers & restricting access to the base controller在哪里定位多个 Rails 控制器使用的方法和限制对基本控制器的访问
【发布时间】:2011-06-08 13:29:12
【问题描述】:

我有两个控制器(比如 ArticlesController 和 PostsController),它们使用大约 5 种相同的方法。这是仅有的两个使用这 5 种方法的控制器,所以他们不觉得它们应该位于 ApplicationController 中。目前,我创建了一个基础控制器(比如 ContentController),然后现有的两个控制器继承自这个基础。

我的问题是 - 这是减少重复的最佳方法吗?

第二个问题 - 我如何确保这些方法只能由从基类继承的控制器访问?在上面的示例中,我不希望直接访问 ContentController。

谢谢!

【问题讨论】:

  • 刚刚更新了我的答案,仅供参考... 2 年后 ;)

标签: ruby-on-rails ruby model-view-controller inheritance


【解决方案1】:

我认为拥有一个 ArticlesController 和 PostsController 都继承自共同祖先是完全可以接受的。这就是继承的意义不是吗?如果您不希望直接从 ContentController 公开操作,只需确保没有路由路由到 ContentController。

另一种方法是为这些功能制作一个模块,并根据需要包含该模块。假设您想调用模块“我的函数”:

/lib/my_functions.rb:

module MyFunctions
  def function1
    ...
  end

  def function2
    ...
  end

  ...
end

然后,只要您需要这些功能,只需包含该模块:

class PostsController < ActionController::Base
  include MyFunctions
  ...
end

class ArticlesController < ActionController::Base
  include MyFunctions
  ...
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    相关资源
    最近更新 更多