Controller initializer function?

Hi, i’m a php developer and am used to developing using the zend
framework, recently i have discovered the wonders of rails, and have a
simple question:

In zend in your controller you can make a function called init() which
will always run for every action inside that controller, how can i
make an initializer function in a rails controller?

I’ve searched but havent found much on initializer functions. Thanks.

Look up before_filter which does exactly what you describe. The
before_filter runs before every action inside a controller. Rails is
filled with filters on models and controllers. Specifically though check
out:

http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html

Basically,

In a controller

SomeController < AC::Base

before_filter :some_method_name

your actions here

protected

def some_method_name

some filter action here

end

You can even qualify filters so they run only for certain actions or
skip certain actions:

before_filter :some_method, :only => [‘action’, ‘action2’]

or if you want even run the filter based on a inline condition using a
plugin:

http://giantrobots.thoughtbot.com/2008/2/15/when-rails-plugin

thats just what i needed^^, thanks.

I was going to suggest you could make a definition called initialize and
put your code in there, but before_filter is better and initialize
probably doesn’t work in controllers.

initialize is a RUBY thing, not a Rails thing, so it should work
anywhere. However, the before/after/around filters are the
appropriate solution.

@Evan: Be sure to use inheritance to your advantage. You can drop a
single method (e.g., filter) into the ApplicationController
(application.rb) and it will be inherited by ALL controllers in your
application. If any of the individual controllers want to ‘opt out’
you can use skip_filter to bypass it.