开发者

Callback for classes defined inside a Module

Ruby already has several built-in callbacks. Is there a callb开发者_开发技巧ack for such case? Kinda like method_added, but for classes (or constants) inside a module, instead of instance methods inside a class.


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


You could try this approach, by defining your own def_class method:

module M
  def self.const_missing(name)
    const_set(name, Class.new)
  end

  def self.def_class(klass, &block)
    class_added(klass.name)
    klass.class_eval(&block)
  end
end

module M
  def self.class_added(klass)
    puts "new class added: #{klass}"
  end

  def_class Hello do
    def hello
      puts "hello!"
    end
  end
end

h = M::Hello.new.hello #=> "hello!"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜