如何使"self"在Mixin模块中引用我的类(即使在方法的上下文之外声明了该类)?

如何使

问题描述:

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

I am using Ruby on Rails 3.2.2. I have implemented a Mixin module for a Article model class and I would like to get the self to refer to Article (even, for example, if it stated outside the context of a method). That is, I am trying to make the following:

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

上面的代码生成以下错误:

The above code generates the following error:

undefined method `my_article_method?' for MyModule

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

How can I run the my_article_method? in the above so that the self (or something else) refers to the Article model class?

只需使用Concernincluded方法:

module MyModule
  extend ActiveSupport::Concern

  included do
    include MyModule::AnotherModule if self.my_article_method?
  end
end