Forum: Ruby on Rails use code form one controller in another

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.
Tarscher (Guest)
on 2007-02-22 16:06
(Received via mailing list)
Hi all,

Can I use code from one controller in another controller? If so, how
do i  do this?

Thanks
Stijn
Michael S. (Guest)
on 2007-02-22 17:11
(Received via mailing list)
On Thursday 22 February 2007, Tarscher wrote:
> Can I use code from one controller in another controller? If so, how
> do i  do this?

You don't. You extract the common code into a third piece. Either an
object that is instantiated in each of the controllers or a mixin
module that is included in each.

Michael

--
Michael S.
mailto:removed_email_address@domain.invalid
http://www.schuerig.de/michael/
Tarscher (Guest)
on 2007-02-22 17:44
(Received via mailing list)
Thanks for the reply,

Where in my rails structure do I put this common code directory wise?
Somewhere in the app director?

Is there some tutorial on this?

Stijn
Alex T. (Guest)
on 2007-02-22 18:14
Tarscher wrote:
> Thanks for the reply,
>
> Where in my rails structure do I put this common code directory wise?
> Somewhere in the app director?
>
> Is there some tutorial on this?
>
> Stijn

There may be a more official way to do this, but what I've done is to
create a file 'application.rb' in the controller directory and put
shared functions in there.  Works nice for validation or db queries etc.

I do the same for views / helpers by using a application_helper.rb file.

I don't believe you can use the same code from a controller and in a
view - I've had to put a couple functions in both files.  Though I may
be wrong.
Ed Hickey (Guest)
on 2007-02-22 18:27
(Received via mailing list)
> Where in my rails structure do I put this common code directory wise?

> > Somewhere in the app director?
> > Is there some tutorial on this?


http://www.robbyonrails.com/articles/2007/02/09/ex...


-ed
Chris W. (Guest)
on 2007-02-22 22:37
(Received via mailing list)
On 2/22/07, Alex T. <removed_email_address@domain.invalid> wrote:

> I don't believe you can use the same code from a controller and in a
> view - I've had to put a couple functions in both files.  Though I may
> be wrong.

You can.

class ApplicationController < ActionController::Base
   helper_method :current_user, :logged_in?
end

This will make the 'current_user' and 'logged_in?' controller methods
available to all views.

--
Chris W.
http://errtheblog.com
This topic is locked and can not be replied to.