Just one request unless you stuff it in the session hash.
If the method you use to set it is a before_filter, then it will be
available to everything further down the chain, but only for that one
request.
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 Controller instance variables get shared in weird ways with
helpers and views? Can someone describe exactly where they are
available and where they are not? Same with Helper instance variables.
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).
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.
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 Makes total sense now. Pulls a couple of
loose
threads re: Rails architecture together for me. Thanks again.
Best regards,
Bill
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.