gpt4 book ai didi

ruby - 了解类方法的 method_added

转载 作者:数据小太阳 更新时间:2023-10-29 06:34:30 25 4
gpt4 key购买 nike

我想在将实例和类方法添加到某个类时施展魔法。因此我尝试了以下方法:

module Magic
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def method_added(name)
puts "class method '#{name}' added"
end
def some_class_method
puts "some class method"
end
end
end

class Foo
include Magic
def self.method_added(name)
puts "instance method #{name} added"
end
end

这种方法适用于实例方法,不适用于类方法。我该如何解决?有什么建议吗?

最佳答案

您正在寻找 singleton_method_added:

module Magic
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def method_added(name)
puts "instance method '#{name}' added"
end

def singleton_method_added(name)
puts "class method '#{name}' added"
end
end
end

class Foo
include Magic

def bla
end

def blubb
end

def self.foobar
end
end

输出:

instance method 'bla' added
instance method 'blubb' added
class method 'foobar' added

尽情享受吧!

关于ruby - 了解类方法的 method_added,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com