Ruby on Rails Filters
Filters run in respect to controller actions - before, after or around them. These methods can halt the action processing by redirecting or set up common data to every action in the controller.
Rails support three types of filter methods:
Rails before filters are executed before the code in action controller is executed. The before filters are defined at the top of a controller class that calls them. To set it up, you need to call before_filter method.
class UserController < ApplicationController before_filter :verify_password def verify_password ... end end
In this example, method verify_password is applied as a before filter. Before any action method will be called, verify_password method is called.
Rails after filters are executed after the code in action controller is executed. Just like before filters, after filters are also defined at the top of a controller class that calls them. To set it up, you need to call after_filter method.
class UserController < ApplicationController before_filter :verify_password def verify_password ... end end class PhotoController < ApplicationController after_filter :resize_photo def resize_photo ... end end
In this example, method resize_photo is applied as an after filter.
Rails around filters contain codes that are executed both before and after controller's code is executed. They are generally used when you need both before and after filter. Its implementation is little bit different and more complex than other two filters. It is generally defined by a common class which contains both before and after methods.
class ActionLogger def before(controller) @start_time = Time.new end def after(controller) @end_time = Time.now @elapsed_time = @end_time.to_f - @start_time.to_f @action = controller.action_name # next save this logging detail to a file or database table end end
In the ActionLogger class, before method captures time an action is started and after method captures time an action completes, the elapsed time.
Let us see how ActionLogger class works as an around filter. In your controller class, simply add around_filter method and pass an instance of ActionLogger as a parameter.
class PhotoController < ApplicationController around_filter ActionLogger.new end