有没有办法避免(在尝试时引发错误)定义具有特定名称的方法,例如Foo#bar
? (用例将是Foo#bar
已定义的时候,我想避免重写该方法,但这与问题无关。)我假设的是:
class Foo
prohibit_definition :bar
end
...
# Later in some code
class Foo
def bar
...
end
end
# => Error: `Foo#bar' cannot be defined
答案 0 :(得分:5)
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
答案 1 :(得分:4)
也许您可以捕获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