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)?

混江龙づ霸主 提交于 2019-12-10 00:25:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!