如何跳过Ruby on Rails中的过滤器自定义类?

时间:2013-02-02 14:40:53

标签: ruby-on-rails before-filter

我有一个Ruby on Rails控制器,before_filter使用自定义类:

class ApplicationController
  before_filter CustomBeforeFilter      
end

我有另一个继承自ApplicationController的控制器,我想跳过CustomBeforeFilter

class AnotherController < ApplicationController
  skip_before_filter CustomBeforeFilter
end

这不起作用。 before_filter仍在执行中。

如何在使用自定义类的过滤器之前跳过Ruby on Rails?

3 个答案:

答案 0 :(得分:2)

您可以将自定义类包装在如下方法中:

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

然后根据需要禁用该过滤器

答案 1 :(得分:2)

类回调在添加到过滤器链时会被分配一个随机回调名称。我能想到的唯一方法是首先找到回调的名称:

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

如果您想在控制器中使用更清洁的东西,可以覆盖ApplicationController中的skip_before_filter方法并使其可供所有控制器使用:

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

然后你可以这样做:

class AnotherController < ApplicationController
  skip_before_filter CustomBeforeFilter
end

答案 2 :(得分:1)

如果当前控制器是您要跳过的控制器,最简单的解决方案是从before_filter方法返回:

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

编辑:

根据phoet建议,您也可以使用controller.controller_name代替params[:controller]