Scott W. Bradley

in which scottwb thinks out loud

Fork me on GitHub

Enumerate Rails 3 Controller Filters

| Comments

There may come a time that you wish to programatically get a list of what before_filters, after_filters, and around_filters are set on a given controller class in Rails. In Rails 2, there was a filter_chain method on ActionController::Base that you could use to do this. That method is gone in Rails 3 in favor of something much more magical.

One reason for wanting to do this is simply for debugging. Sometimes you just need to sanity check that filters are being applied in the order you think they are. Especially when they’re being added dynamically by various plugins.

In Rails 3, I find it convenient to add a few utility methods to ApplicationController that list out the symbol names of all the filters on any given controller:

application_controller.rb View Gist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Add these methods to your ApplicationController. Then, any controller
# that inherits from it will have these methods and can programmatically
# determine what filters it has set.
class ApplicationController < ActionController::Base

  def self.filters(kind = nil)
    all_filters = _process_action_callbacks
    all_filters = all_filters.select{|f| f.kind == kind} if kind
    all_filters.map(&:filter)
  end

  def self.before_filters
    filters(:before)
  end

  def self.after_filters
    filters(:after)
  end

  def self.around_filters
    filters(:around)
  end

end

With that in hand, you can do something like this:

1
2
3
4
5
6
7
8
9
10
11
ree-1.8.7-2011.03 :002 > ap PostsController.before_filters
[
    [0] :verify_authenticity_token,
    [1] "_callback_before_1",
    [2] :set_geokit_domain,
    [3] :block_internet_explorer,
    [4] :add_authenticity_token,
    [5] :always_mobile,
    [6] :find_post,
    [7] :set_meta_tags
]

Comments