Filters are essentially callback methods that are run before, after, or “around” a controller action.
- Before filter methods are run before a controller action and therefore may halt the request cycle. A common before filter is one which requires a user to be logged in for an action to be performed.
- After filter methods are run after a controller action and therefore cannot stop the action from being performed but do have access to the response data that is about to be sent to the client.
- Around filter methods are “wrapped around” a controller action. They can therefore control the execution of an action as well as execute code before and/or after the action is performed.
For example, in a website where changes have an approval workflow, an administrator could be able to preview them easily with an around filter as follows:
Note that an around filter also wraps rendering. In particular, in the example above, if the view reads from the database (e.g., via a scope), it will do so within the transaction and thus present the data to preview. You can also choose not to yield and build the response yourself, in which case the action will not be run.
The order of execution is a bit tricky and is important to understand clearly. Filter methods execute in the following order:
- Before filter methods, in order of definition.
- Around filter methods, in order of definition.
- After filter methods, in reverse order.
Also, because of the way Ruby instantiates classes, the filter methods of a parent class’ before will be run before those of its child classes.