Controller-wide instance variable

Is it possible to declare an instance variable in a controller that is
available to every action without defining the variable in every action?

On 6/5/06, ryan [email protected] wrote:

Is it possible to declare an instance variable in a controller that is
available to every action without defining the variable in every action?

You have two main options (though there are others):

The firstis to use a session variable:

session[:name] = value

The other is a “class variable”:

@@variable = value

That will create a “class variable” which is available to every instance
of
the controller. However, because the Rails environment will get reloaded
on
each request in development mode, the value won’t persist across
requests.
In production mode, I think the behavior is indeterminate and depends on
your setup.

ryan wrote:

Is it possible to declare an instance variable in a controller that is
available to every action without defining the variable in every action?

You could do it in a before_filter.


Jack C.
[email protected]

Ryan:

Consider using before_filter instead of initialize (It’s a good habit
and you may want to do something else in initialize, or use the same
code over and over)

application.rb

def do_stuff
@variable_to_display = “hello world”
end

store_contrller.rb

before_filter :do_stuff

login_controller.rb

before_filter :do_stuff, :except=>[:login, :logout]

Thanks for the input. I suppose before_filter would be more flexible
than initialize.

Brian H. wrote:

Ryan:

Consider using before_filter instead of initialize (It’s a good habit
and you may want to do something else in initialize, or use the same
code over and over)

application.rb

def do_stuff
@variable_to_display = “hello world”
end

store_contrller.rb

before_filter :do_stuff

login_controller.rb

before_filter :do_stuff, :except=>[:login, :logout]

Thanks for the help.

I just found what I wanted. I didn’t need persistence across actions,
but actually to just repeat some code for every action (but I didn’t
want to actually duplicate code.)

I used the initialize() fuction in the controller class.

Justin B. wrote:

On 6/5/06, ryan [email protected] wrote:

Is it possible to declare an instance variable in a controller that is
available to every action without defining the variable in every action?

You have two main options (though there are others):

The firstis to use a session variable:

session[:name] = value

The other is a “class variable”:

@@variable = value

That will create a “class variable” which is available to every instance
of
the controller. However, because the Rails environment will get reloaded
on
each request in development mode, the value won’t persist across
requests.
In production mode, I think the behavior is indeterminate and depends on
your setup.