Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do authentication, caching, or auditing before the intended action is performed. Or to do localization or output compression after the action has been performed.
Filters have access to the request, response, and all the instance variables set by other filters in the chain or by the action (in the case of after filters). Additionally, it’s possible for a pre-processing before_filter to halt the processing before the intended action is processed by returning false or performing a redirect or render. This is especially useful for filters like authentication where you’re not interested in allowing the action to be performed if the proper credentials are not in order.
Filter inheritance
Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without affecting the superclass. For example:
class BankController < ActionController::Base
before_filter :audit
private
def audit
# record the action and parameters in an audit log
end
end
class VaultController < BankController
before_filter :verify_credentials
private
def verify_credentials
# make sure the user is allowed into the vault
end
end
Now any actions performed on the BankController will have the audit method called before. On the VaultController, first the audit method is called, then the verify_credentials method. If the audit method returns false, then verify_credentials and the intended action are never called.
Filter types
A filter can take one of three forms: method reference (symbol), external class, or inline method (proc). The first is the most common and works by referencing a protected or private method somewhere in the inheritance hierarchy of the controller by use of a symbol. In the bank example above, both BankController and VaultController use this form.
Using an external class makes for more easily reused generic filters, such as output compression. External filter classes are implemented by having a static filter method on any class and then passing this class to the filter method. Example:
class OutputCompressionFilter
def self.filter(controller)
controller.response.body = compress(controller.response.body)
end
end
class NewspaperController < ActionController::Base
after_filter OutputCompressionFilter
end
The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can manipulate them as it sees fit.
The inline method (using a proc) can be used to quickly do something small that doesn’t require a lot of explanation. Or just as a quick test. It works like this:
class WeblogController < ActionController::Base
before_filter { |controller| false if controller.params["stop_action"] }
end
As you can see, the block expects to be passed the controller after it has assigned the request to the internal variables. This means that the block has access to both the request and response objects complete with convenience methods for params, session, template, and assigns. Note: The inline method doesn’t strictly have to be a block; any object that responds to call and returns 1 or -1 on arity will do (such as a Proc or an Method object).
Filter chain ordering
Using before_filter and after_filter appends the specified filters to the existing chain. That’s usually just fine, but some times you care more about the order in which the filters are executed. When that’s the case, you can use prepend_before_filter and prepend_after_filter. Filters added by these methods will be put at the beginning of their respective chain and executed before the rest. For example:
class ShoppingController
before_filter :verify_open_shop
class CheckoutController
prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock
The filter chain for the CheckoutController is now :ensure_items_in_cart, :ensure_items_in_stock, :verify_open_shop. So if either of the ensure filters return false, we’ll never get around to see if the shop is open or not.
You may pass multiple filter arguments of each type as well as a filter block. If a block is given, it is treated as the last argument.
Around filters
In addition to the individual before and after filters, it’s also possible to specify that a single object should handle both the before and after call. That’s especially useful when you need to keep state active between the before and after, such as the example of a benchmark filter below:
class WeblogController < ActionController::Base
around_filter BenchmarkingFilter.new
# Before this action is performed, BenchmarkingFilter#before(controller) is executed
def index
end
# After this action has been performed, BenchmarkingFilter#after(controller) is executed
end
class BenchmarkingFilter
def initialize
@runtime
end
def before
start_timer
end
def after
stop_timer
report_result
end
end
Filter chain skipping
Some times its convenient to specify a filter chain in a superclass that’ll hold true for the majority of the subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters they would like to be relieved of. Examples
class ApplicationController < ActionController::Base
before_filter :authenticate
end
class WeblogController < ApplicationController
# will run the :authenticate filter
end
class SignupController < ApplicationController
# will not run the :authenticate filter
skip_before_filter :authenticate
end
Filter conditions
Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to exclude or the actions to include when executing the filter. Available conditions are +:only+ or +:except+, both of which accept an arbitrary number of method references. For example:
class Journal < ActionController::Base
# only require authentication if the current action is edit or delete
before_filter :authorize, :only => [ :edit, :delete ]
private
def authorize
# redirect to login unless authenticated
end
end
When setting conditions on inline method (proc) filters the condition must come first and be placed in parentheses.
class UserPreferences < ActionController::Base
before_filter(:except => :new) { # some proc ... }
# ...
end
- after_filter
- append_after_filter
- append_around_filter
- append_before_filter
- around_filter
- before_filter
- prepend_after_filter
- prepend_around_filter
- prepend_before_filter
- skip_after_filter
- skip_before_filter
Alias for append_after_filter
The passed filters will be appended to the array of filters that’s run after actions on this controller are performed.
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 195
195: def append_after_filter(*filters, &block)
196: conditions = extract_conditions!(filters)
197: filters << block if block_given?
198: add_action_conditions(filters, conditions)
199: append_filter_to_chain('after', filters)
200: end
The passed filters will have their before method appended to the array of filters that’s run both before actions on this controller are performed and have their after method prepended to the after actions. The filter objects must all respond to both before and after. So if you do append_around_filter A.new, B.new, the callstack will look like:
B#before
A#before
A#after
B#after
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 222
222: def append_around_filter(*filters)
223: conditions = extract_conditions!(filters)
224: for filter in filters.flatten
225: ensure_filter_responds_to_before_and_after(filter)
226: append_before_filter(conditions || {}) { |c| filter.before(c) }
227: prepend_after_filter(conditions || {}) { |c| filter.after(c) }
228: end
229: end
The passed filters will be appended to the array of filters that’s run before actions on this controller are performed.
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 174
174: def append_before_filter(*filters, &block)
175: conditions = extract_conditions!(filters)
176: filters << block if block_given?
177: add_action_conditions(filters, conditions)
178: append_filter_to_chain('before', filters)
179: end
Alias for append_around_filter
Alias for append_before_filter
The passed filters will be prepended to the array of filters that’s run after actions on this controller are performed.
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 204
204: def prepend_after_filter(*filters, &block)
205: conditions = extract_conditions!(filters)
206: filters << block if block_given?
207: add_action_conditions(filters, conditions)
208: prepend_filter_to_chain("after", filters)
209: end
The passed filters will have their before method prepended to the array of filters that’s run both before actions on this controller are performed and have their after method appended to the after actions. The filter objects must all respond to both before and after. So if you do prepend_around_filter A.new, B.new, the callstack will look like:
A#before
B#before
B#after
A#after
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 239
239: def prepend_around_filter(*filters)
240: for filter in filters.flatten
241: ensure_filter_responds_to_before_and_after(filter)
242: prepend_before_filter { |c| filter.before(c) }
243: append_after_filter { |c| filter.after(c) }
244: end
245: end
The passed filters will be prepended to the array of filters that’s run before actions on this controller are performed.
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 183
183: def prepend_before_filter(*filters, &block)
184: conditions = extract_conditions!(filters)
185: filters << block if block_given?
186: add_action_conditions(filters, conditions)
187: prepend_filter_to_chain('before', filters)
188: end
Removes the specified filters from the after filter chain. Note that this only works for skipping method-reference filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out of many sub-controllers need a different hierarchy.
You can control the actions to skip the filter for with the :only and :except options, just like when you apply the filters.
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 274
274: def skip_after_filter(*filters)
275: if conditions = extract_conditions!(filters)
276: remove_contradicting_conditions!(filters, conditions)
277: conditions[:only], conditions[:except] = conditions[:except], conditions[:only]
278: add_action_conditions(filters, conditions)
279: else
280: for filter in filters.flatten
281: write_inheritable_attribute("after_filters", read_inheritable_attribute("after_filters") - [ filter ])
282: end
283: end
284: end
Removes the specified filters from the before filter chain. Note that this only works for skipping method-reference filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out of many sub-controllers need a different hierarchy.
You can control the actions to skip the filter for with the :only and :except options, just like when you apply the filters.
[ show source ]
# File vendor/rails/actionpack/lib/action_controller/filters.rb, line 256
256: def skip_before_filter(*filters)
257: if conditions = extract_conditions!(filters)
258: remove_contradicting_conditions!(filters, conditions)
259: conditions[:only], conditions[:except] = conditions[:except], conditions[:only]
260: add_action_conditions(filters, conditions)
261: else
262: for filter in filters.flatten
263: write_inheritable_attribute("before_filters", read_inheritable_attribute("before_filters") - [ filter ])
264: end
265: end
266: end