Forum: Ruby on Rails two controllers needing the same method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Raj S. (Guest)
on 2007-05-03 19:51
(Received via mailing list)
Two of my controllers need access to same method. I instantly put them
in
ApplicationController and the problem was solved.

Now I'm thinking my ApplicationController is getting polluted because
there
are many cases in which a method is needed by two or three controllers.
What
are the other ways to handle such cases.

One case could be to have a base controller and then to extend these
controllers so that they get the common methods. Well I don't like it
that
much.

Any thoughts.
Frederick C. (Guest)
on 2007-05-03 19:53
You could have a module with the common methods and include it in
controllers needing those methods

Fred
John M. (Guest)
on 2007-05-06 06:26
Raj S. wrote:
> Two of my controllers need access to same method. I instantly put them
> in
> ApplicationController and the problem was solved.
>
> Now I'm thinking my ApplicationController is getting polluted because
> there
> are many cases in which a method is needed by two or three controllers.
> What
> are the other ways to handle such cases.
>
> One case could be to have a base controller and then to extend these
> controllers so that they get the common methods. Well I don't like it
> that
> much.
>
> Any thoughts.

Group the methods into categories.  Put each category in a file in
#{RAILS_ROOT}/lib/aplication_controller  (or where ever).

Easy (but less orginized) way.  In each file put:

AplicationController <ActionController::Base
  #function go here
end

and require the files in Application.rb

More complex (but Ruby like ) way.  Each file defines a module with the
functions.  Include the module in either ApplicationController or
individual Controllers.

JFM
This topic is locked and can not be replied to.