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:

  1. Around
  2. Before
  3. After

Asking around, some people thought that the ordering was:

  1. Before
  2. Around
  3. 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