Filter Order in Rails
Today I learned a lot about the way that Rails handles filters, that the methods: before_filter, around_filter and after_filter
I ran into a bug while working on the work to upgrade from rails 3.2 to 4.0 that I thought might be caused by a change in the way that filters are applied. Let’s see if you can guess what the following code would output.
Sample Controller
I initially thought that filters were sorted into different queues, then processed in the order:
- Around
- Before
- After
Asking around, some people thought that the ordering was:
- Before
- Around
- After
(although that may have been because of the way I framed the question)
It turns out both are wrong.
The output of that controller would be this:
Filters are processed in the order they are defined.
You can see that this is the intended behaviour in this test for rails: filters_test.rb
That makes a lot of sense after some thought. You’d want to be able to have some before_filters run before around_filters, but before_filters to run inside of around_filters.
tl;dr Filters are processed in the order they are defined