0

我正在使用 Ruby on Rails 3.2.2。我已经为模型类实现了一个 Mixin 模块Article,我想self引用它Article(即使,例如,如果它在方法的上下文之外声明)。也就是说,我正在尝试执行以下操作:

module MyModule
  extend ActiveSupport::Concern

  # Note: The following is just a sample code (it doesn't work for what I am 
  # trying to accomplish) since 'self' isn't referring to Article but to the
  # MyModule itself.
  include MyModule::AnotherMyModule if self.my_article_method?

  ...
end

上面的代码会产生以下错误:

undefined method `my_article_method?' for MyModule

如何my_article_method?在上面运行,以便self(或其他)引用Article模型类?

4

2 回答 2

3

你可以使用self.included钩子:

def self.included(klass)
  klass.include MyModule::AnotherMyModule if klass.my_article_method?
end

我宁愿把逻辑放在实际的Article课堂上。该模块不需要知道它包含的类:

class Article
  include MyModule
  include MyModule::AnotherModule if self.my_article_method?
end
于 2012-09-28T13:10:53.957 回答
0

只需使用Concern'included方法:

module MyModule
  extend ActiveSupport::Concern

  included do
    include MyModule::AnotherModule if self.my_article_method?
  end
end
于 2012-09-28T13:22:57.473 回答