1

当我的项目越来越大时,我需要编写一些方法,但是 application_controller 的私有方法和助手并没有提供足够的空间来存储所有扩展。

因此,我查看了存储在 /lib 文件夹中的自定义类和方法。

但是我仍然有一些我无法解决的问题:

- 我什么时候应该使用“class << self”?我有一个类,用于计算两个数字数组之间的差异,然后返回具有该数字中间值的新数组。我习惯了这样的代码:

x = MyClass.new
x.calculate(array1, array2)

然后我将我的类的方法放入“class << self; end”以使用类而无需初始化。是正确的解决方案吗?

-我什么时候应该使用自定义模块?是否总是需要“包含”或“要求”它们?请告诉我您项目中的模块,您什么时候使用它们?

- 如何在控制器中调用助手的方法?我想在ajax响应中使用。例如,我使用辅助方法“users_for_output”,如果有 ajax 调用,我的应用程序应该只将用户呈现为文本,然后使用 javascript 处理它。

4

1 回答 1

1

1) You don't have to instantiate the class to invoke a static method, i.e.

MyUtil.do_something 

Vs.

MyUtil.new.do_something 

In my project I keep such methods static.

2) You can use modules when want to share a set of functionality across classes. Read this mixin vs inheritance discussion. You will get a good idea about when to use modules.

2.1) The included method is intended for initializing the module variables. You don't need to use it if you don't have anything initialize.

3) If you want to expose a controller method as a helper method use the helper_method call in your ApplicationController class.

class ApplicationController < ActionController::Base
  helper_method :user_for_output
end
于 2010-03-07T02:05:22.017 回答