如何使"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?
答
只需使用Concern
的included
方法:
module MyModule
extend ActiveSupport::Concern
included do
include MyModule::AnotherModule if self.my_article_method?
end
end