Controller-wide instance variable


#1

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


#2

On 6/5/06, ryan removed_email_address@domain.invalid 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.


#3

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.
removed_email_address@domain.invalid


#4

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]


#5

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]


#6

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 removed_email_address@domain.invalid 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.