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?
source to share
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
source to share
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]
source to share