views:

24

answers:

1

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.

+1  A: 

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
KandadaBoggu