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.
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With