【问题标题】:How to check if one of two before_filters pass (Rails)? before_filter :check1 || before_filter :check2 ?如何检查两个 before_filters 之一是否通过(Rails)? before_filter :check1 || before_filter :check2 ?
【发布时间】:2014-10-02 11:37:01
【问题描述】:

我在 application_controller.rb 中有 check_feature 方法

  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

我将它用作过滤器(before_filter)。

在我的控制器中,我想说点什么,例如启用访问控制器的两个功能中的至少一个。

如果我这样做:

check_feature :feature1
check_feature :feature2

我需要启用功能 1 和功能 2 才能通过过滤器。

我想要类似的东西:

check_feature :feature1 || check_feature :feature2

有什么想法吗?

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4 before-filter


【解决方案1】:

创建一个能够识别多个功能的包装器。大致如下:

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

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多