Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback for classes defined inside a Module

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.

like image 409
Daniel Ribeiro Avatar asked Nov 16 '10 04:11

Daniel Ribeiro


2 Answers

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
like image 115
Ryan Calhoun Avatar answered Sep 22 '22 11:09

Ryan Calhoun


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!"
like image 32
horseyguy Avatar answered Sep 22 '22 11:09

horseyguy