Lifespan of a Controller instance variable

Hi Robert,

Robert Head wrote:

If I drop an instance variable into my controller, how long does it survive?

For example,

So, how long does @foo survive? For the duration of one request? Or something else?

In general, instance variables live for one request/response cycle. It can be shorter than that though if, for example, you do a redirect to another controller.

hth, Bill

I believe all controller instance variables are made available to views and helpers. A good rule of thumb is only set instance variables for things you really need to get access to in the view, otherwise just us a local/temp. Furthermore, if there are instance variables that you access throughout your app (that are set in ApplicationController for instance), add some accessor methods to encapsulate them (in the same way that session and params encapsulate the data).

Bill Walton wrote:

Hi Robert,

Robert Head wrote:

If I drop an instance variable into my controller, how long does it survive?

For example,

So, how long does @foo survive? For the duration of one request? Or something else?

In general, instance variables live for one request/response cycle. It can be shorter than that though if, for example, you do a redirect to another controller.

Don't mean to be boor, but a redirect *is* a response... it's the "yeah, I got yer post, now here's where to go for the next page" response.

So, I'd say that instance variables live for one request/response cycle... period.

b

Hi Ben,

Ben Munat wrote:

Don't mean to be boor, but a redirect *is* a response... it's the "yeah, I got yer post, now here's where to go for the next page" response.

Thanks for posting this. I'd never really grokked the fundamentals of why the instance variables didn't live through a redirect. The mental model I had was that the cycle ended with a render and that server-side processing that included a redirect was occurring as one 'unit'. I'd put the life-span question in the "That's just how it works. Here's how to deal with it." pile. Your post caused me to reread the doc on redirect and there it was in black and white. Duh :wink: Makes total sense now. Pulls a couple of loose threads re: Rails architecture together for me. Thanks again.

Best regards, Bill