有没有办法避免(尝试时引发错误)定义具有特定名称的方法,例如Foo#bar
?(一个用例是 whenFoo#bar
已经定义,我想避免该方法被覆盖,但这与问题无关。)我假设如下:
class Foo
prohibit_definition :bar
end
...
# Later in some code
class Foo
def bar
...
end
end
# => Error: `Foo#bar' cannot be defined
class Class
def method_added(method_name)
raise "So sad, you can't add" if method_name == :bad
end
end
class Foo
def bad
puts "Oh yeah!"
end
end
#irb> RuntimeError: So sad, you can't add
# from (irb):3:in `method_added'
# from (irb):7
method_added(
也许您可以在类的) 中捕获回调Module
并检查方法名称,如果添加的方法不符合您的条件,则删除它。然后你可以提出一个错误。
不是你想要的,但我认为足够接近。
class Class
def method_added(method_name)
if method_name == :bar
remove_method :bar
puts "#{method_name} cannot be added to #{self}"
end
end