通过在“包含”方法中评估它们来模块化 class 级方法调用

Modularizing class-level method calls by evaluating them in `included` methods

我正在处理一个 Rails 项目,该项目使用 flip gem 作为功能标志。我们有一个功能 class,您可以在其中声明要使用的各种功能标志,

# app/models/feature.rb

class Feature < ActiveRecord::Base
  extend   Flip::Declarable
  strategy Flip::DeclarationStrategy

  feature :ivans_feature_A
  feature :ivans_feature_B
  feature :ivans_feature_C

  feature :kramers_feature_X
  feature :kramers_feature_X
end

随着项目的增长,我们在此文件中声明的功能标志的数量也在增加。一位同事建议我们将相关的功能声明分解成单独的模块来组织事情。

我找到了一种方法来做到这一点,但这不是我以前见过的模式,所以我想知道是否有更标准的方法。我正在为我想组合在一起的每一组功能定义命名空间模块:

app/models/features/ivans_features.rb

module Features::IvansFeatures
  def self.included(base)
    base.feature :ivans_feature_A
    base.feature :ivans_feature_B
    base.feature :ivans_feature_C
  end
end

app/models/features/kramers_features.rb

module Features::KramersFeatures
  def self.included(base)
    base.feature :kramers_feature_X
    base.feature :kramers_feature_Y
  end
end

...并将它们包含在特征模型中:

# app/models/feature.rb

class Feature < ActiveRecord::Base
  extend   Flip::Declarable
  strategy Flip::DeclarationStrategy

  include  Features::IvansFeatures
  include  Features::KramersFeatures
end

为了使用 运行 回调 class 的某些方法调用的唯一目的,将模块混合到 class 中是不是很奇怪?

在您的 Feature class 中,您可以 extend ActiveSupport::Concern 然后执行类似

的操作
included do
  feature :kramers_feature_X
end