Filter Inheritance

Controller inheritance hierarchies share filters downward. Your average Rails application
has an ApplicationController from which all other controllers inherit, so if you
wanted to add filters that are always run no matter what, that would be the place to do so.

class ApplicationController < ActionController::Base
after_filter :compress

Subclasses can also add and/or skip already defined filters without affecting the superclass.
For example, consider the two related classes below, and how they interact.

class BankController < ActionController::Base
before_filter :audit
protected
def audit
# record this controller’s actions and parameters in an audit log
end
end

class VaultController < BankController
before_filter :verify_credentials
protected
def verify_credentials
# make sure the user is allowed into the vault
end
end

 

Any actions performed on BankController (or any of its subclasses) will
cause the audit method to be called before the requested action is exe-
cuted. On the VaultController, first the audit method is called, followed by
verify_credentials, because that’s the order in which the filters were specified. (Fil-
ters are executed in the class context where they’re declared, and the BankController
has to be loaded before VaultController, since it’s the parent class.)
If the audit method happens to call render or redirect_to for whatever reason,
verify_credentials and the requested action are never called. This is called halting
the filter chain.

One response to “Filter Inheritance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s