本文介绍了回调在模块内部定义的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby已经有几个内置回调.有这种情况的回调吗?有点像method_added,但用于模块内部的类(或常量),而不是用于类内部的实例方法.

Ruby already has several built-in callbacks. Is there a callback for such case? Kinda like method_added, but for classes (or constants) inside a module, instead of instance methods inside a class.

推荐答案

据我所知,没有什么与您所描述的完全一样.但是,这是使用Class::inherited创建自己的方法.

As far as I know, there is nothing exactly like what you're describing. However, here's how you could create your own, using Class::inherited.

module MyModule
  def self.class_added(klass)
    # ... handle it
  end
  class ::Class
    alias_method :old_inherited, :inherited
    def inherited(subclass)
      MyModule.class_added(subclass) if /^MyModule::\w+/.match subclass.name
      old_inherited(subclass)
    end
  end
end

module MyModule
  # now add classes
end

这篇关于回调在模块内部定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 01:34