Last Updated: February 25, 2016
·
1.069K
· hopsoft

Rails before_render filter

Recently I had the need to hook into the Rails page lifecycle. Specifically - after the action ran but before the view rendered.

My particular use case required that I pull Devise error messages off the resource & add them to the flash before the view templates rendered. Here's how I did it.

# application_controller.rb
class ApplicationController < ActionController::Base

  def render(*args)
    add_devise_errors_to_flash if devise_controller?
    super # <- view render happens here
  end

  def add_devise_errors_to_flash
    if resource.errors.present?
      # add errors to flash
    end
  end 

end

Enjoy!