Rails Controllers: Before, After, and Around Filters




Rails Coach show

Summary: In your Rails controllers you have filters you can place on incoming requests, outgoing responses, or wrap around your actions. Before filters are run on requests before the request gets to the controller’s action. It can return a response itself and completely bypass the action. The most common use of before filters is validating a user’s authentication before granting them access to the action designated to handle their request. I’ve also seen them used to load a resource from the database, check permissions on a resource, or manage redirects under other circumstances. After filters are run after the action completes. It can modify the response. Most of the time if something is done in an after filter, it can be done in the action itself, but if there is some logic to be run after running any of a set of actions, then an after filter is a good place to do it. Generally, I’ve seen after and around filters used for logging. Around filters may have logic before and after the action being run. It simply yields to the action in whatever place is necessary. Note that it doesn’t need to yield to the action and may run without doing so like a before filter. You can use around filters for exception handling, setup and teardown, and a myriad of other cases.