推荐答案
在 Ruby 中,常用的钩子方法包括:
includedextendedprependedinheritedmethod_missingmethod_addedsingleton_method_addedconst_missing
这些钩子方法允许开发者在特定事件发生时执行自定义逻辑。
本题详细解读
included
当一个模块被包含到另一个模块或类中时,included 钩子方法会被调用。通常用于在模块被包含时执行一些初始化操作。
// www.javascriptcn.com code example
module MyModule
def self.included(base)
puts "MyModule included in #{base}"
end
end
class MyClass
include MyModule
endextended
当一个模块被扩展到一个对象时,extended 钩子方法会被调用。
module MyModule
def self.extended(base)
puts "MyModule extended to #{base}"
end
end
obj = Object.new
obj.extend(MyModule)prepended
当一个模块被前置到另一个模块或类中时,prepended 钩子方法会被调用。
// www.javascriptcn.com code example
module MyModule
def self.prepended(base)
puts "MyModule prepended to #{base}"
end
end
class MyClass
prepend MyModule
endinherited
当一个类被继承时,inherited 钩子方法会被调用。
class MyClass
def self.inherited(subclass)
puts "MyClass inherited by #{subclass}"
end
end
class MySubClass < MyClass
endmethod_missing
当调用一个不存在的方法时,method_missing 钩子方法会被调用。
class MyClass
def method_missing(method_name, *args)
puts "Method #{method_name} not found"
end
end
obj = MyClass.new
obj.some_undefined_methodmethod_added
当一个方法被添加到类或模块中时,method_added 钩子方法会被调用。
class MyClass
def self.method_added(method_name)
puts "Method #{method_name} added"
end
def my_method
end
endsingleton_method_added
当一个单例方法被添加到对象中时,singleton_method_added 钩子方法会被调用。
class MyClass
def self.singleton_method_added(method_name)
puts "Singleton method #{method_name} added"
end
def self.my_singleton_method
end
endconst_missing
当引用一个未定义的常量时,const_missing 钩子方法会被调用。
class MyClass
def self.const_missing(const_name)
puts "Constant #{const_name} not found"
end
end
MyClass::UNDEFINED_CONSTANT这些钩子方法为 Ruby 提供了强大的元编程能力,允许开发者在特定事件发生时执行自定义逻辑。