/ devise

Easy filters for Devise controllers

Here's a way to add filters to your controllers without subclassing the Devise controllers.

For example, I have a prepare_something method that I want to apply as a before_filter to all of the Devise controller actions.

First, create a module in config/initializers/devise_filters.rb where we’ll implement a method to add all the filters to Devise that we want. We also need to make sure this module calls this method upon initialization so that our filters get added upon startup (this is important for the production environment).

 # Put this somewhere it will get auto-loaded, like config/initializers
module DeviseFilters
  def self.add_filters
    # Example of adding a before_filter to all the Devise controller actions we care about.
    ].each do |controller|
      controller.before_filter :prepare_for_mobile
    # Example of adding one selective before_filter.
    Devise::SessionsController.before_filter :void_my_sessions, :only => :destroy

We need an extra setting to make it work for development mode because in development mode each request reloads all the Devise classes and all our filters are gone.

To address this, we need to add a bit of code to the end of the initializer block in config/environments/development.rb

 # Add this in your development.rb
MyApp::Application.configure do
  config.to_prepare do

This tells Rails to call your DeviseFilters.add_filters method before each new request in development mode, after the classes have been reloaded.

In production mode, controller classes gets cached at start of application, so above snippet wont be needed for production mode.