19

我喜欢ActiveSupport::Concern

它使向您的类添加功能变得容易,而且语法很好。

无论如何,在 Rails 3.2 中,InstanceMethods 模块已被弃用。如果我理解正确,我们应该在included中定义我们的方法(实际上它只是在模块的主体中​​):

# edit: don't do this! The method definition should just be in the body of the module
included do
    def my_method; end
end

我只是想知道是否有人知道他们为什么决定这样做?

4

1 回答 1

29

让我们看一下您首先链接的示例。

module TagLib
  extend ActiveSupport::Concern

  module ClassMethods
    def find_by_tags()
      # ...
    end
  end

  module InstanceMethods
    def tags()
      # ...
    end
  end 
end

当您将 TagLib 包含到您的类中时,AS Concern 会自动使用 ClassMethods 模块扩展该类并包含 InstanceMethods 模块。

class Foo
  include TagLib
  # is roughly the same as
  include TagLib::InstanceMethods
  extend TagLib::ClassMethods
end

但是您可能注意到我们已经包含了 TagLib 模块本身,因此其中定义的方法已经可以作为类的实例方法使用。那你为什么想要一个单独的 InstanceMethods 模块呢?

module TagLib
  extend ActiveSupport::Concern

  module ClassMethods
    def find_by_tags()
      # ...
    end
  end

  def tags()
    # ...
  end
end

class Foo
  include TagLib
  # does only `extend TagLib::ClassMethods` for you
end
于 2012-01-03T03:33:07.113 回答