助手、方法和类组织
当我的项目成长时,我需要编写一些方法,但是 application_controller 的私有方法和帮助程序没有提供足够的空间来存储所有扩展。
因此,我查看了存储在 /lib 文件夹中的自定义类和方法。
但我仍然有一些问题无法解决:
- 我什么时候应该使用“class << self”?我有一个类,用于计算两个数字数组之间的差异,然后返回具有该数字的中间值的新数组。我习惯了这样的代码:
x = MyClass.new
x.calculate(array1, array2)
然后我将我的类的方法放入“class << self; end”中以使用类而不进行初始化。这是正确的解决方案吗?
- 我什么时候应该使用自定义模块?是否总是需要“包含”或“要求”它们?请告诉我您项目中的模块,您什么时候使用它们?
- 如何在控制器中调用helper的方法?我想在ajax响应中使用。例如,我使用辅助方法“users_for_output”,如果有 ajax 调用,我的应用程序应该仅将用户呈现为文本,然后使用 javascript 对其进行处理。
When my project is growing up, I need to write some methods, but application_controller's private methods and helpers aren't provide enough space to store all extensions.
So I have looked at custom classes and methods, which are stored in the /lib folder.
But i still have some questions, which i can't solve:
-When should I use "class << self"? I have a class, to calculate difference between two arrays of numbers, and then return new array with a middle values of that numbers. I used to such code:
x = MyClass.new
x.calculate(array1, array2)
And then I have placed my class' methods into "class << self; end" to use class without initialization. Is it right solution?
-When should i use custom modules? Is it always need to 'include' or 'require' them? Please tell me about your modules in your projects, when do you use them?
-How can I call helper's method in the controller? I want to use in in ajax responce. For example I use helper method 'users_for_output', and if there was ajax call, my app should render only users as text, to process it with javascript after.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1)您不必实例化类来调用静态方法,即
Vs。
在我的项目中,我将这些方法保持静态。
2)当想要跨类共享一组功能时,可以使用模块。阅读此 mixin 与继承的讨论。您将很好地了解何时使用模块。
2.1)
included
方法用于初始化模块变量。如果没有任何初始化,则不需要使用它。3) 如果您想将控制器方法公开为辅助方法,请使用 ApplicationController 类中的
helper_method
调用。1) You don't have to instantiate the class to invoke a static method, i.e.
Vs.
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.