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.
Danny H. (Guest)
on 2005-12-16 01: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
Joe Van D. (Guest)
on 2005-12-16 01:53
(Received via mailing list)
On 12/15/05, Danny H. <removed_email_address@domain.invalid> 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.
Abdur-Rahman A. (Guest)
on 2005-12-16 01:53
(Received via mailing list)
Well the controler gets created every time a action is called, HTTP is a
stateless protocol : )
Jamie M. (Guest)
on 2005-12-16 01:53
(Received via mailing list)
On Thu, 2005-12-15 at 15:47 -0800, Danny H. 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
Steven S. (Guest)
on 2005-12-16 02: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.
Joe Van D. (Guest)
on 2005-12-18 05:53
(Received via mailing list)
On 12/15/05, Steven S. <removed_email_address@domain.invalid> 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.