ActiveSupport::Concern 放置在包含块内或模块主体中的代码

ActiveSupport::Concern code placed inside the included block or in the module body

假设我有以下命名空间和一个 Base 模块,它定义了一些可以重用的方法

module MyNameSpace
  module Magic
    extend ActiveSupport::Concern

    class_methods do 
      def magic_field(field_name)
        # Defines methods and attributes based on field name
      end
    end
  end
end

有什么区别(如果有的话)
module MyNameSpace
  module Foo
    extend ActiveSupport::Concern
    include Magic

    included do
      magic_field(:foo)
    end
  end
end

module MyNameSpace
  module Foo
    extend ActiveSupport::Concern

    included do
      include Magic
      magic_field(:foo)
    end
  end
end

(问题是关于 include Magicincluded 块外部或内部的区别)

当问题包含在 class 中时,includeclass_methods 允许接收方 class 继承这些方法。

included 添加实例方法,而 class_methods 添加 class 方法。

来源:Rails Concerns Docs

另一方面,如果您的问题是 include Magic 的位置差异,那么 class 的功能没有差异。