Dispatcher callbacks
Published about 7 years ago

Changeset 7640 introduced 2 new members to rails family of callbacks : before_dispatch and after_dispatch. These callbacks are executed before/after every request, and provides you with hooks at much higher level than normal before_filter and after_filter of ActionController::Base.

Also, note that after_filter are not executed if your action raises an exception. So dispatcher callbacks might be a better fit for performance related logging, etc. where the final outcome of your controller doesn’t really matter, and you want your callbacks to be executed for each and every request.

For example, try the following in your environment.rb :

require 'dispatcher'
module ActionController
  class Dispatcher
    def start_timer
      @start_time = Time.now
    end

    def end_timer
      RAILS_DEFAULT_LOGGER.info "="*100
      RAILS_DEFAULT_LOGGER.info "      URL : #{@request.url}"
      RAILS_DEFAULT_LOGGER.info "     Real : #{Time.now-@start_time} seconds"
      RAILS_DEFAULT_LOGGER.info "Less Real : #{@response.headers["X-Runtime"]} seconds"
      RAILS_DEFAULT_LOGGER.info "="*100
    end

    before_dispatch :start_timer
    after_dispatch :end_timer
  end
end