How can I pass a custom class before the filter in Ruby on Rails?

I have a Ruby on Rails Controller before_filter

using a custom class:

class ApplicationController
  before_filter CustomBeforeFilter      
end

      

I have another controller inherited from ApplicationController

, where I would like to skip CustomBeforeFilter

:

class AnotherController < ApplicationController
  skip_before_filter CustomBeforeFilter
end

      

This does not work. before_filter

is still running.

How can I skip Ruby on Rails in front of a filter that uses a custom class?

+3


source to share


3 answers


Class callbacks are assigned a random callback name when they are added to the filter chain. The only way I can do this is to find the callback name first:

skip_before_filter _process_action_callbacks.detect {|c| c.raw_filter == CustomBeforeFilter }.filter

      

If you want a little cleaner in your controllers, you can override the skip_before_filter method in the ApplicationController and make it available to all controllers:



class ApplicationController < ActionController::Base
  def self.skip_before_filter(*names, &block)
    names = names.map { |name|
      if name.class == Class
        _process_action_callbacks.detect {|callback| callback.raw_filter == name }.filter
      else
        name
      end
    }

    super
  end
end

      

Then you could do:

class AnotherController < ApplicationController
  skip_before_filter CustomBeforeFilter
end

      

+2


source


you can just wrap your own class in a method:

before_filter :custom
def custom
  CustomBeforeFilter.filter(self)
end

      



and then disable this filter wherever you want

+2


source


The simplest solution would be to return from your before_filter method if the current controller is the one you want to skip:

class CustomBeforeFilter
  def self.filter(controller)
    return if params[:controller] == "another"
    # continue filtering logic
  end
end

      

EDIT:

Following phoet's advice, you can also use controller.controller_name

instead ofparams[:controller]

+1


source







All Articles