问题
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
How can I run the my_article_method?
in the above so that the self
(or something else) refers to the Article
model class?
回答1:
Just use Concern
's included
method instead:
module MyModule
extend ActiveSupport::Concern
included do
include MyModule::AnotherModule if self.my_article_method?
end
end
回答2:
You can use the self.included
hook:
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. 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
来源:https://stackoverflow.com/questions/12640645/how-to-get-the-self-to-refer-to-a-my-class-inside-a-mixin-module-even-if-it-i