Forum: Ruby on Rails initialize called more than once?

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.
A93215744828b77596275194b733e597?d=identicon&s=25 Danny Hendargo (Guest)
on 2005-12-16 00:50
(Received via mailing list)
Hi,

In my test case below, it seems that 'initialize' is called everytime
'hello' is called. Is this by design, a bug, or my pilot error?

    class FooController < ApplicationController

        def initialize
            print "\n initialize \n"
        end

        def hello
            print "\n hello \n"
        end
    end

I thought initialize will be called exactly once when the controller is
constructed and not when an action is executed.

Thanks for your help and sorry if duplicate,

-Danny
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2005-12-16 00:53
(Received via mailing list)
On 12/15/05, Danny Hendargo <danny@newavenue.net> wrote:
>
>         def hello
>             print "\n hello \n"
>         end
>     end
>
> I thought initialize will be called exactly once when the controller is
> constructed and not when an action is executed.

On every request, a controller object is created.  When the controller
object is created, the initialized function is called.
03cb7371db223067d0daab54e1f95cb2?d=identicon&s=25 Abdur-Rahman Advany (Guest)
on 2005-12-16 00:53
(Received via mailing list)
Well the controler gets created every time a action is called, HTTP is a
stateless protocol : )
Eb234d1ee9f1dcd334657d7c5c1b1c4d?d=identicon&s=25 Jamie Macey (jamie)
on 2005-12-16 00:53
(Received via mailing list)
On Thu, 2005-12-15 at 15:47 -0800, Danny Hendargo wrote:
>
>         def hello
>             print "\n hello \n"
>         end
>     end
>
> I thought initialize will be called exactly once when the controller is
> constructed and not when an action is executed.

This is correct, it's just that a new FooController is being created
(instantiated, whatever) for each request.

- Jamie
4353600bbb6b6e0950e62f7f44e49dd5?d=identicon&s=25 Steven Smith (Guest)
on 2005-12-16 01:23
(Received via mailing list)
If you're in dev mode, I believe the controller would be reloaded
with every request so you would see initialize called for each
invocation of hello.
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2005-12-18 04:53
(Received via mailing list)
On 12/15/05, Steven Smith <ssmith@fiveruns.com> wrote:
> If you're in dev mode, I believe the controller would be reloaded
> with every request so you would see initialize called for each
> invocation of hello.

Controllers get re-constructed on every invocation of every action, no
matter if you're in development, test, or production mode.
This topic is locked and can not be replied to.