[英]How to get the `self` to refer to a my class inside a Mixin module (even if it is stated outside the context of a method)?
I am using Ruby on Rails 3.2.2. 我正在使用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). 我已经为
Article
模型类实现了一个Mixin模块,并且我想让self
引用Article
(即使,例如,如果它在方法的上下文之外声明)。 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
How can I run the my_article_method?
如何运行
my_article_method?
in the above so that the self
(or something else) refers to the Article
model class? 在上面使
self
(或其他)引用Article
模型类?
You can use the self.included
hook: 您可以使用
self.included
挂钩:
def self.included(klass)
klass.include MyModule::AnotherMyModule if klass.my_article_method?
end
I'd rather put the logic on the actual Article
class. 我宁愿将逻辑放在实际的
Article
类上。 The module shouldn't need to know about the classes it is included in: 该模块不需要了解包含在其中的类:
class Article
include MyModule
include MyModule::AnotherModule if self.my_article_method?
end
Just use Concern
's included
method instead: 只需使用
Concern
的included
方法即可:
module MyModule
extend ActiveSupport::Concern
included do
include MyModule::AnotherModule if self.my_article_method?
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.