Search code examples
ruby-on-railsruby-on-rails-4before-filter

How to check if one of two before_filters pass (Rails)? before_filter :check1 || before_filter :check2 ?


I have check_feature method in application_controller.rb

  def self.check_feature(feature, options = {})
    before_filter(options) { |controller| controller.check_feature_now(feature) }
  end

  def check_feature_now(feature)
    raise MyError.new(401, I18n.t('exception.feature_not_enabled'), ErrorCodes::FEATURE_NOT_ENABLED) unless feature_enabled?(feature)
  end

And I'm using this as a filter (before_filter).

In my controller I wanna say something, like at least one of the two features enabled to access the controller.

If I do something like:

check_feature :feature1
check_feature :feature2

I'll need feature1 AND feature2 enabled to pass the filter.

I want something like:

check_feature :feature1 || check_feature :feature2

Any ideas?


Solution

  • Create a wrapper that will be aware of multiple features. Something along these lines:

    def self.require_one_of(*features, options = {})
      before_filter(options) do |controller|
        unless features.any?{|f| controller.feature_enabled?(f)}
          raise MyError.new(401, I18n.t('exception.feature_not_enabled'), ErrorCodes::FEATURE_NOT_ENABLED)
        end
    
      end
    end
    
    
    # then
    require_one_of :feature1, :feature2